Calculate Uniform Distribution

Uniform Distribution Calculator & Guide :root { –primary-color: #004a99; –success-color: #28a745; –background-color: #f8f9fa; –text-color: #333; –border-color: #ddd; –card-background: #fff; –shadow: 0 2px 5px rgba(0,0,0,0.1); } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(–background-color); color: var(–text-color); line-height: 1.6; margin: 0; padding: 0; } .container { max-width: 960px; margin: 20px auto; padding: 20px; background-color: var(–card-background); border-radius: 8px; box-shadow: var(–shadow); } header { text-align: center; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 1px solid var(–border-color); } header h1 { color: var(–primary-color); margin-bottom: 10px; } .calculator-section { margin-bottom: 40px; padding: 30px; background-color: var(–card-background); border-radius: 8px; box-shadow: var(–shadow); } .calculator-section h2 { color: var(–primary-color); text-align: center; margin-bottom: 25px; } .loan-calc-container { display: flex; flex-direction: column; gap: 20px; } .input-group { display: flex; flex-direction: column; gap: 8px; } .input-group label { font-weight: bold; color: var(–primary-color); } .input-group input[type="number"], .input-group select { padding: 12px; border: 1px solid var(–border-color); border-radius: 5px; font-size: 1rem; box-sizing: border-box; } .input-group input[type="number"]:focus, .input-group select:focus { outline: none; border-color: var(–primary-color); box-shadow: 0 0 0 2px rgba(0, 74, 153, 0.2); } .input-group .helper-text { font-size: 0.85rem; color: #666; } .error-message { color: #dc3545; font-size: 0.85rem; margin-top: 5px; min-height: 1.2em; /* Prevent layout shift */ } .button-group { display: flex; gap: 15px; margin-top: 25px; justify-content: center; flex-wrap: wrap; } .btn { padding: 12px 25px; border: none; border-radius: 5px; cursor: pointer; font-size: 1rem; font-weight: bold; transition: background-color 0.3s ease, transform 0.2s ease; text-decoration: none; display: inline-block; text-align: center; } .btn-primary { background-color: var(–primary-color); color: white; } .btn-primary:hover { background-color: #003366; transform: translateY(-1px); } .btn-secondary { background-color: #6c757d; color: white; } .btn-secondary:hover { background-color: #5a6268; transform: translateY(-1px); } .btn-success { background-color: var(–success-color); color: white; } .btn-success:hover { background-color: #218838; transform: translateY(-1px); } .results-container { margin-top: 30px; padding: 25px; background-color: #e9ecef; border-radius: 8px; border: 1px solid #ced4da; } .results-container h3 { color: var(–primary-color); margin-top: 0; text-align: center; margin-bottom: 20px; } .main-result { font-size: 2.5rem; font-weight: bold; color: var(–primary-color); text-align: center; margin-bottom: 20px; padding: 15px; background-color: #d1ecf1; border-radius: 5px; border: 1px solid #bee5eb; } .intermediate-results div, .formula-explanation { margin-bottom: 15px; font-size: 1.1rem; color: #444; } .intermediate-results span { font-weight: bold; color: var(–primary-color); } .formula-explanation { font-style: italic; color: #555; border-top: 1px dashed var(–border-color); padding-top: 15px; margin-top: 20px; } table { width: 100%; border-collapse: collapse; margin-top: 25px; box-shadow: var(–shadow); } thead { background-color: var(–primary-color); color: white; } th, td { padding: 12px 15px; text-align: left; border: 1px solid var(–border-color); } tbody tr:nth-child(even) { background-color: #f2f2f2; } caption { font-size: 1.1rem; font-weight: bold; color: var(–primary-color); margin-bottom: 15px; caption-side: top; text-align: left; } canvas { display: block; margin: 30px auto; max-width: 100%; border: 1px solid var(–border-color); border-radius: 5px; background-color: var(–card-background); } .article-section { margin-top: 40px; padding: 30px; background-color: var(–card-background); border-radius: 8px; box-shadow: var(–shadow); } .article-section h2, .article-section h3 { color: var(–primary-color); margin-bottom: 15px; } .article-section h2 { border-bottom: 2px solid var(–primary-color); padding-bottom: 8px; } .article-section p { margin-bottom: 15px; } .article-section ul, .article-section ol { margin-left: 20px; margin-bottom: 15px; } .article-section li { margin-bottom: 8px; } .faq-item { margin-bottom: 20px; padding: 15px; background-color: #f8f9fa; border-radius: 5px; border: 1px solid #e0e0e0; } .faq-item h3 { margin-top: 0; margin-bottom: 10px; color: var(–primary-color); cursor: pointer; font-size: 1.15rem; } .faq-item p { display: none; /* Hidden by default */ margin-bottom: 0; } .faq-item.open p { display: block; } .internal-links-section ul { list-style: none; padding: 0; } .internal-links-section li { margin-bottom: 15px; } .internal-links-section a { color: var(–primary-color); text-decoration: none; font-weight: bold; } .internal-links-section a:hover { text-decoration: underline; } .internal-links-section span { display: block; font-size: 0.9rem; color: #555; margin-top: 5px; } @media (min-width: 768px) { .container { margin: 30px auto; padding: 30px; } .button-group { justify-content: flex-start; } }

Uniform Distribution Calculator

Understand and calculate probabilities for continuous uniform distributions.

Uniform Distribution Calculator

The minimum possible value of the distribution.
The maximum possible value of the distribution.
The specific value at which to evaluate the CDF or PDF.
Cumulative Distribution Function (P(X ≤ x)) Probability Density Function (f(x))
Choose whether to calculate the CDF or PDF.

Calculation Results

Chart showing the PDF and CDF of the uniform distribution.
Uniform Distribution Parameters
Parameter Value Unit
Lower Bound (a) Units
Upper Bound (b) Units
Range (b – a) Units
Probability Density Function (PDF) 1/Units
Expected Value (E[X]) Units
Variance (Var(X)) Units²

What is Uniform Distribution?

The uniform distribution, also known as the rectangular distribution, is a fundamental concept in probability theory and statistics. It describes a scenario where all outcomes within a given range are equally likely. Imagine a perfectly fair spinner that can land anywhere on a circle; the probability of it landing in any specific segment of the same size is identical. This contrasts with distributions like the normal distribution, where outcomes cluster around a central mean.

Who should use it? Anyone working with data or processes where randomness is expected to be evenly spread across a defined interval can benefit from understanding the uniform distribution. This includes fields like:

  • Physics: Modeling random errors within a measurement range, or the position of particles.
  • Engineering: Simulating random variations in manufacturing tolerances.
  • Computer Science: Generating random numbers within a specific range for simulations or algorithms.
  • Finance: As a simplified model for certain asset price movements over short, undefined periods, or for modeling random arrival times.
  • Quality Control: Assessing variations in product dimensions.

Common Misconceptions: A frequent misunderstanding is that "uniform" means a single, constant value. However, in probability, it means that *any value within the specified range has the same probability density*. Another misconception is confusing the probability density function (PDF) with the probability itself. For continuous distributions, the PDF at a single point is technically zero; probability is calculated over an interval.

Uniform Distribution Formula and Mathematical Explanation

The continuous uniform distribution is defined by two parameters: the lower bound, denoted as 'a', and the upper bound, denoted as 'b'. All values between 'a' and 'b' (inclusive) are equally likely.

Probability Density Function (PDF)

The PDF, denoted as f(x), represents the relative likelihood for a continuous random variable to take on a given value. For a uniform distribution, the PDF is constant within the interval [a, b] and zero elsewhere.

The formula is:

$f(x) = \begin{cases} \frac{1}{b-a} & \text{for } a \le x \le b \\ 0 & \text{otherwise} \end{cases}$

The value $\frac{1}{b-a}$ ensures that the total area under the PDF curve equals 1, a fundamental property of probability distributions.

Cumulative Distribution Function (CDF)

The CDF, denoted as F(x), gives the probability that the random variable X is less than or equal to a specific value x, i.e., $P(X \le x)$.

The formula is:

$F(x) = \begin{cases} 0 & \text{for } x b \end{cases}$

This means the probability increases linearly from 0 at 'a' to 1 at 'b'.

Expected Value (Mean)

The expected value, E[X], is the average value we expect to get from the distribution over many trials. For a uniform distribution, it's simply the midpoint of the interval.

$E[X] = \frac{a+b}{2}$

Variance

The variance, Var(X), measures the spread or dispersion of the distribution around its mean.

$Var(X) = \frac{(b-a)^2}{12}$

Variables Table

Uniform Distribution Variables
Variable Meaning Unit Typical Range
a Lower bound of the distribution Units Any real number
b Upper bound of the distribution Units b > a
x Specific value for PDF/CDF calculation Units Any real number
f(x) Probability Density Function value 1/Units 0 to 1/(b-a)
F(x) Cumulative Distribution Function value (Probability) Probability (0 to 1) 0 to 1
E[X] Expected Value (Mean) Units a to b
Var(X) Variance Units² ≥ 0

Practical Examples (Real-World Use Cases)

Example 1: Bus Arrival Times

Suppose a bus arrives at a stop every 15 minutes, and you arrive at the stop at a random time. Your waiting time can be modeled by a uniform distribution. Let's assume the bus schedule is precise, and the arrival interval is exactly 15 minutes. If you arrive at a random moment within that 15-minute window, your waiting time is uniformly distributed between 0 minutes (if you just missed the bus) and 15 minutes (if you arrive just as the bus departs).

Inputs:

  • Lower Bound (a): 0 minutes
  • Upper Bound (b): 15 minutes

Calculations:

  • PDF: $f(x) = \frac{1}{15-0} = \frac{1}{15}$ (for 0 ≤ x ≤ 15)
  • CDF at x=5 minutes: $F(5) = \frac{5-0}{15-0} = \frac{5}{15} \approx 0.333$
  • Expected Waiting Time: $E[X] = \frac{0+15}{2} = 7.5$ minutes
  • Variance: $Var(X) = \frac{(15-0)^2}{12} = \frac{225}{12} = 18.75$ minutes²

Interpretation: The PDF of 1/15 means that for any specific minute within the 15-minute interval, the probability density is constant. The CDF of 0.333 at 5 minutes indicates a 33.3% chance you will wait 5 minutes or less. On average, you can expect to wait 7.5 minutes. The variance of 18.75 indicates the typical spread of waiting times around the average.

Example 2: Manufacturing Tolerance

A machine part is designed to have a length of 10 cm, but due to manufacturing variations, the actual length is uniformly distributed between 9.9 cm and 10.1 cm.

Inputs:

  • Lower Bound (a): 9.9 cm
  • Upper Bound (b): 10.1 cm

Calculations:

  • PDF: $f(x) = \frac{1}{10.1-9.9} = \frac{1}{0.2} = 5$ (for 9.9 ≤ x ≤ 10.1)
  • CDF at x=10.05 cm: $F(10.05) = \frac{10.05-9.9}{10.1-9.9} = \frac{0.15}{0.2} = 0.75$
  • Expected Length: $E[X] = \frac{9.9+10.1}{2} = \frac{20}{2} = 10$ cm
  • Variance: $Var(X) = \frac{(10.1-9.9)^2}{12} = \frac{(0.2)^2}{12} = \frac{0.04}{12} \approx 0.00333$ cm²

Interpretation: The PDF value of 5 means the density is high within this tight tolerance range. A CDF of 0.75 at 10.05 cm implies a 75% probability that a manufactured part will have a length of 10.05 cm or less. The expected length is exactly the target of 10 cm, and the small variance indicates minimal deviation from this average. This is crucial for quality control to ensure parts meet specifications.

How to Use This Uniform Distribution Calculator

  1. Define Your Range: Identify the minimum possible value (Lower Bound, 'a') and the maximum possible value (Upper Bound, 'b') for your random variable. Enter these into the respective input fields. Ensure 'b' is greater than 'a'.
  2. Specify the Value of Interest: Enter the specific value 'x' for which you want to calculate either the Probability Density Function (PDF) or the Cumulative Distribution Function (CDF).
  3. Select Calculation Type: Choose whether you want to calculate the PDF (probability density at a single point) or the CDF (probability of being less than or equal to 'x') using the dropdown menu.
  4. Calculate: Click the "Calculate" button. The calculator will instantly display the results.

How to Read Results:

  • Main Result: This will show either the calculated PDF value (if PDF was selected) or the CDF value (if CDF was selected).
  • Intermediate Values: You'll see the calculated PDF, CDF, Expected Value (mean), and Variance for the given bounds.
  • Formula Explanation: A brief description of the formula used for the selected calculation type.
  • Chart: Visualizes the PDF (a flat line) and CDF (a rising line) across the distribution range.
  • Table: Summarizes the key parameters (a, b, range, PDF, E[X], Var(X)) of the uniform distribution.

Decision-Making Guidance:

  • Use the CDF to determine the probability of an outcome falling within a certain range (e.g., $P(X \le x)$ or $P(a \le X \le x)$).
  • The PDF helps understand the density of outcomes across the interval.
  • The Expected Value gives you the average outcome over many trials.
  • The Variance quantifies the spread of possible outcomes.

Click "Copy Results" to easily share or save your findings. Use the "Reset" button to start fresh with default values.

Key Factors That Affect Uniform Distribution Results

While the uniform distribution is conceptually simple, several factors influence its parameters and the interpretation of its results:

  1. Range Width (b – a): This is the most critical factor. A wider range means the probability density function (PDF) value $\frac{1}{b-a}$ will be lower, indicating a more spread-out distribution. Conversely, a narrower range leads to a higher PDF value. The variance is directly proportional to the square of the range width, meaning wider ranges have significantly higher variability.
  2. Lower Bound (a): This sets the starting point of the distribution. Shifting 'a' (while keeping 'b' constant) changes the interval and thus the mean and variance. For example, shifting the interval [0, 10] to [5, 15] increases the mean from 5 to 10 and the variance remains the same since the range width is unchanged.
  3. Upper Bound (b): Similar to 'a', 'b' defines the end of the interval. Changes in 'b' directly affect the range width, PDF, mean, and variance.
  4. Value of x: The specific point 'x' at which you evaluate the CDF or PDF is crucial. For the CDF, $F(x) = \frac{x-a}{b-a}$, the probability increases linearly as 'x' moves from 'a' towards 'b'. The PDF is constant within the range but is zero outside it.
  5. Units of Measurement: While the mathematical structure remains the same, the units of the bounds (e.g., meters, seconds, dollars) dictate the units of the expected value (same units) and variance (units squared). Consistency in units is vital for correct interpretation.
  6. Assumption of Uniformity: The results are only valid if the underlying process truly exhibits a uniform distribution. If outcomes are actually clustered (like in a normal distribution) or follow a different pattern, the uniform distribution model and its calculated results will be misleading. This assumption is key in financial modeling, where asset returns are rarely perfectly uniform.
  7. Discrete vs. Continuous: This calculator assumes a *continuous* uniform distribution. If your outcomes are discrete (e.g., rolling a die), you would use a discrete uniform distribution, where each specific outcome has an equal probability, but the PDF concept differs.

Frequently Asked Questions (FAQ)

What is the difference between PDF and CDF in a uniform distribution?

The Probability Density Function (PDF), $f(x)$, describes the relative likelihood of a value occurring at a specific point. For a continuous uniform distribution, it's a constant value ($\frac{1}{b-a}$) within the range [a, b] and zero elsewhere. The Cumulative Distribution Function (CDF), $F(x)$, gives the probability that the random variable is less than or equal to a specific value x ($P(X \le x)$). It increases linearly from 0 to 1 across the range [a, b].

Can the PDF value be greater than 1?

Yes, the PDF value *can* be greater than 1. The PDF represents probability *density*, not probability itself. Probability is represented by the *area* under the PDF curve. For distributions with a very narrow range (small $b-a$), the PDF value $\frac{1}{b-a}$ can indeed exceed 1. However, the CDF value (which represents probability) will always be between 0 and 1.

What does an expected value of 7.5 mean in the bus example?

An expected value of 7.5 minutes means that if you were to repeat the process of arriving at the bus stop randomly many, many times, the average waiting time across all those instances would approach 7.5 minutes. It's the long-term average outcome.

How is variance useful for a uniform distribution?

Variance (or its square root, standard deviation) quantifies the spread or dispersion of the possible outcomes. A higher variance means the waiting times or measurements are more spread out from the average. A lower variance indicates outcomes are clustered more tightly around the mean. For the uniform distribution, variance is solely dependent on the width of the interval $(b-a)^2 / 12$.

Is the uniform distribution used in finance?

While less common than distributions like the normal distribution for modeling asset returns due to the assumption of constant volatility, the uniform distribution can be used in finance for specific scenarios. Examples include modeling random arrival times for transactions, simulating random interest rate fluctuations within a narrow band over a short period, or as a component in more complex Monte Carlo simulations. It's often a simplification.

What happens if b = a?

If the upper bound 'b' equals the lower bound 'a', the range $(b-a)$ becomes zero. This leads to division by zero in the PDF and CDF formulas, which is mathematically undefined for a continuous distribution. In practice, this scenario collapses the distribution into a single point, essentially becoming a discrete distribution where the value is fixed at 'a' with probability 1. Our calculator will show an error or handle this as an invalid input.

How does the uniform distribution relate to random number generation?

Many pseudo-random number generators (PRNGs) are designed to produce sequences of numbers that approximate a continuous uniform distribution over the interval [0, 1]. These generated numbers can then be scaled and shifted to simulate variables from any uniform distribution with bounds 'a' and 'b' using the formula: $Y = a + (b-a) \times U$, where U is a random number from [0, 1].

Related Tools and Internal Resources

© 2023 Your Financial Website. All rights reserved.

var chartInstance = null; // Global variable to hold chart instance function getElement(id) { return document.getElementById(id); } function validateInput(value, id, min, max, allowEmpty) { var errorElement = getElement(id + "Error"); errorElement.textContent = ""; // Clear previous error if (!allowEmpty && (value === null || value === "")) { errorElement.textContent = "This field is required."; return false; } if (value === "") return true; // Allow empty if allowed var numValue = parseFloat(value); if (isNaN(numValue)) { errorElement.textContent = "Please enter a valid number."; return false; } if (min !== null && numValue max) { errorElement.textContent = "Value must be no more than " + max + "."; return false; } return true; } function calculateUniformDistribution() { var lowerBoundInput = getElement("lowerBound"); var upperBoundInput = getElement("upperBound"); var xValueInput = getElement("xValue"); var probabilityTypeSelect = getElement("probabilityType"); var resultsContainer = getElement("resultsContainer"); var mainResultElement = getElement("mainResult"); var pdfValueElement = getElement("pdfValue"); var cdfValueElement = getElement("cdfValue"); var expectedValueElement = getElement("expectedValue"); var varianceValueElement = getElement("varianceValue"); var formulaExplanationElement = getElement("formulaExplanation"); var tableLowerBound = getElement("tableLowerBound"); var tableUpperBound = getElement("tableUpperBound"); var tableRange = getElement("tableRange"); var tablePdf = getElement("tablePdf"); var tableExpectedValue = getElement("tableExpectedValue"); var tableVariance = getElement("tableVariance"); var a = parseFloat(lowerBoundInput.value); var b = parseFloat(upperBoundInput.value); var x = parseFloat(xValueInput.value); var type = probabilityTypeSelect.value; var errors = false; if (!validateInput(lowerBoundInput.value, "lowerBound")) errors = true; if (!validateInput(upperBoundInput.value, "upperBound")) errors = true; if (!validateInput(xValueInput.value, "xValue")) errors = true; if (a >= b) { getElement("upperBoundError").textContent = "Upper bound must be greater than lower bound."; errors = true; } if (errors) { resultsContainer.style.display = "none"; return; } var range = b – a; var pdfValue = 0; var cdfValue = 0; var expectedValue = (a + b) / 2; var varianceValue = Math.pow(range, 2) / 12; if (x >= a && x <= b) { pdfValue = 1 / range; cdfValue = (x – a) / range; } else if (x b pdfValue = 0; cdfValue = 1; } var formula = ""; var mainResultText = ""; if (type === "pdf") { mainResultText = "PDF (f(x)): " + pdfValue.toFixed(6); formula = "The Probability Density Function (PDF) for a uniform distribution is $f(x) = \\frac{1}{b-a}$ for $a \\le x \\le b$, and 0 otherwise."; } else { mainResultText = "CDF (P(X ≤ x)): " + cdfValue.toFixed(6); formula = "The Cumulative Distribution Function (CDF) for a uniform distribution is $F(x) = \\frac{x-a}{b-a}$ for $a \\le x \\le b$, $F(x)=0$ for $x b$."; } mainResultElement.textContent = mainResultText; pdfValueElement.innerHTML = "PDF (f(x)): " + pdfValue.toFixed(6) + ""; cdfValueElement.innerHTML = "CDF (P(X ≤ x)): " + cdfValue.toFixed(6) + ""; expectedValueElement.innerHTML = "Expected Value (E[X]): " + expectedValue.toFixed(6) + ""; varianceValueElement.innerHTML = "Variance (Var(X)): " + varianceValue.toFixed(6) + ""; formulaExplanationElement.innerHTML = formula; tableLowerBound.textContent = a.toFixed(6); tableUpperBound.textContent = b.toFixed(6); tableRange.textContent = range.toFixed(6); tablePdf.textContent = (1 / range).toFixed(6); tableExpectedValue.textContent = expectedValue.toFixed(6); tableVariance.textContent = varianceValue.toFixed(6); resultsContainer.style.display = "block"; updateChart(a, b, expectedValue); } function resetCalculator() { getElement("lowerBound").value = "0"; getElement("upperBound").value = "10"; getElement("xValue").value = "5"; getElement("probabilityType").value = "cdf"; getElement("lowerBoundError").textContent = ""; getElement("upperBoundError").textContent = ""; getElement("xValueError").textContent = ""; getElement("resultsContainer").style.display = "none"; if (chartInstance) { chartInstance.destroy(); chartInstance = null; } // Clear table content as well getElement("tableLowerBound").textContent = ""; getElement("tableUpperBound").textContent = ""; getElement("tableRange").textContent = ""; getElement("tablePdf").textContent = ""; getElement("tableExpectedValue").textContent = ""; getElement("tableVariance").textContent = ""; } function copyResults() { var mainResult = getElement("mainResult").textContent; var pdfValue = getElement("pdfValue").textContent.replace("PDF (f(x)): ", ""); var cdfValue = getElement("cdfValue").textContent.replace("CDF (P(X ≤ x)): ", ""); var expectedValue = getElement("expectedValue").textContent.replace("Expected Value (E[X]): ", ""); var varianceValue = getElement("varianceValue").textContent.replace("Variance (Var(X)): ", ""); var lowerBound = getElement("lowerBound").value; var upperBound = getElement("upperBound").value; var xValue = getElement("xValue").value; var probabilityType = getElement("probabilityType").options[getElement("probabilityType").selectedIndex].text; var textToCopy = "Uniform Distribution Calculation Results:\n\n"; textToCopy += "Inputs:\n"; textToCopy += "- Lower Bound (a): " + lowerBound + "\n"; textToCopy += "- Upper Bound (b): " + upperBound + "\n"; textToCopy += "- Value (x): " + xValue + "\n"; textToCopy += "- Calculation Type: " + probabilityType + "\n\n"; textToCopy += "Results:\n"; textToCopy += mainResult + "\n"; textToCopy += "PDF (f(x)): " + pdfValue + "\n"; textToCopy += "CDF (P(X ≤ x)): " + cdfValue + "\n"; textToCopy += "Expected Value (E[X]): " + expectedValue + "\n"; textToCopy += "Variance (Var(X)): " + varianceValue + "\n"; navigator.clipboard.writeText(textToCopy).then(function() { alert("Results copied to clipboard!"); }).catch(function(err) { console.error("Failed to copy text: ", err); alert("Failed to copy results. Please copy manually."); }); } function updateChart(a, b, mean) { var canvas = getElement('uniformDistributionChart'); var ctx = canvas.getContext('2d'); // Destroy previous chart instance if it exists if (chartInstance) { chartInstance.destroy(); } var range = b – a; var pdfHeight = 1 / range; var xValues = []; var pdfValues = []; var cdfValues = []; // Generate points for the chart var step = range / 100; for (var i = 0; i = a && x <= b) { pdfValues.push(pdfHeight); } else { pdfValues.push(0); } // CDF calculation if (x b) { cdfValues.push(1); } else { cdfValues.push((x – a) / range); } } // Add points for boundaries if not already included if (!xValues.includes(a)) { xValues.unshift(a); pdfValues.unshift(0); // PDF is 0 just before 'a' cdfValues.unshift(0); } if (!xValues.includes(b)) { xValues.push(b); pdfValues.push(0); // PDF is 0 just after 'b' cdfValues.push(1); } // Ensure chart covers the range slightly extended var chartMinX = a – range * 0.1; var chartMaxX = b + range * 0.1; var chartMaxY = Math.max(pdfHeight, 1) * 1.1; // Adjust max Y for better visualization chartInstance = new Chart(ctx, { type: 'line', data: { labels: xValues, datasets: [{ label: 'PDF (f(x))', data: pdfValues.map(function(val, index) { return {x: xValues[index], y: val}; }), borderColor: 'var(–primary-color)', backgroundColor: 'rgba(0, 74, 153, 0.1)', fill: false, tension: 0, pointRadius: 0 }, { label: 'CDF (F(x))', data: cdfValues.map(function(val, index) { return {x: xValues[index], y: val}; }), borderColor: 'var(–success-color)', backgroundColor: 'rgba(40, 167, 69, 0.1)', fill: false, tension: 0, pointRadius: 0 }] }, options: { responsive: true, maintainAspectRatio: false, scales: { x: { type: 'linear', position: 'bottom', title: { display: true, text: 'Value (x)' }, min: chartMinX, max: chartMaxX }, y: { title: { display: true, text: 'Density / Probability' }, min: 0, max: chartMaxY } }, plugins: { tooltip: { callbacks: { label: function(context) { var label = context.dataset.label || "; if (label) { label += ': '; } if (context.parsed.y !== null) { label += context.parsed.y.toFixed(6); } return label; } } }, legend: { position: 'top', } } } }); } function toggleFaq(element) { var parent = element.parentElement; parent.classList.toggle('open'); } // Initial calculation on load if values are present document.addEventListener('DOMContentLoaded', function() { // Check if inputs have default values and trigger calculation var lowerBound = getElement("lowerBound").value; var upperBound = getElement("upperBound").value; var xValue = getElement("xValue").value; if (lowerBound && upperBound && xValue) { // Small delay to ensure chart canvas is ready setTimeout(function() { calculateUniformDistribution(); }, 100); } }); // Add Chart.js library dynamically if not present if (typeof Chart === 'undefined') { var script = document.createElement('script'); script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js'; script.onload = function() { console.log('Chart.js loaded.'); // Recalculate after chart library is loaded var lowerBound = getElement("lowerBound").value; var upperBound = getElement("upperBound").value; var xValue = getElement("xValue").value; if (lowerBound && upperBound && xValue) { setTimeout(function() { calculateUniformDistribution(); }, 100); } }; document.head.appendChild(script); } else { // If Chart.js is already loaded, ensure calculation runs var lowerBound = getElement("lowerBound").value; var upperBound = getElement("upperBound").value; var xValue = getElement("xValue").value; if (lowerBound && upperBound && xValue) { setTimeout(function() { calculateUniformDistribution(); }, 100); } }

Leave a Comment