Random Variable Simulator Calculator

Generate reproducible samples, examine probability models, compare theory, and run advanced Monte Carlo experiments through one complete simulation workspace.

Simulation workspace

Choose a mode, distribution, parameters, seed, and output controls.

Maximum sample size: 100000
Separate numeric values with commas, semicolons, spaces, or new lines.
Fields change automatically for the selected distribution.
Use thousands for stable summaries and demonstrations.
Reuse a seed to reproduce identical results.
Enter comma-separated numeric outcomes.
Enter probabilities matching each outcome.
Allowed: x, pi, e, arithmetic, powers, exp, log, sqrt, abs, trigonometric functions, floor, ceil, and round.
Advanced simulation settings
Use x to leave values unchanged.
This mode creates two correlated normal variables using a Gaussian construction.

Quick presets

Formula used

Expected value

E[X] = Σ x · P(X = x), for discrete variables
E[X] = ∫ x · f(x) dx, for continuous variables

Variance and standard deviation

Var(X) = E[(X − μ)²] = E[X²] − μ²
SD(X) = √Var(X)

Sample statistics

x̄ = (x₁ + x₂ + … + xₙ) / n
s² = Σ(xᵢ − x̄)² / (n − 1)
SE(x̄) = s / √n

Monte Carlo probability

P(event) ≈ successful simulated outcomes / total simulated outcomes

Correlated normal variables

Y = μᵧ + σᵧ[ρZ₁ + √(1 − ρ²)Z₂]

How to use this calculator

  1. Select a simulation, probability, sampling, multivariable, or fitting mode.
  2. Choose a discrete or continuous probability distribution.
  3. Enter valid parameters for the selected distribution.
  4. Set the number of observations and random seed.
  5. Open advanced settings for transformations and histogram bins.
  6. Run the calculation and review validation messages.
  7. Compare sample statistics against theoretical distribution properties.
  8. Inspect histograms, cumulative plots, Q-Q plots, and convergence.
  9. Download every generated value using CSV or JSON.
  10. Use browser printing to save a formatted PDF report.

Understanding random variable simulation

What is a random variable?

A random variable assigns numbers to uncertain outcomes. It converts chance events into measurable values. Probability distributions describe how those values behave.

A simulation generates possible observations from a selected distribution. Each generated value represents one possible outcome. Repeated outcomes reveal the distribution's overall pattern.

Discrete random variables

Discrete variables have countable possible values. Coin results and customer counts are common examples. Their probabilities are described using probability mass functions.

Bernoulli distributions model one success or failure. Binomial distributions model repeated independent Bernoulli trials. Poisson distributions model event counts during fixed exposure.

Geometric distributions model trials until the first success. Negative binomial distributions extend this idea further. Hypergeometric distributions sample without replacement from finite populations.

Continuous random variables

Continuous variables may take any value across an interval. Heights, waiting times, and lifetimes are common examples. Their probabilities are measured through areas under density curves.

Normal distributions model symmetric variation around a mean. Exponential distributions model memoryless waiting times. Weibull distributions commonly model reliability and component lifetimes.

Gamma distributions support flexible positive-valued shapes. Beta distributions model proportions between zero and one. Lognormal distributions model positive right-skewed measurements.

Random seeds and reproducibility

A random seed initializes the pseudorandom number generator. Reusing the same seed recreates the same sequence. This feature supports auditing, teaching, and experiment comparison.

Changing the seed creates another valid random sample. Different samples naturally produce different summary statistics. This variation is expected rather than erroneous.

Law of large numbers

The law of large numbers concerns long-run averages. Sample means usually approach theoretical expectations as samples increase. Small samples can remain noticeably different.

The running mean chart makes convergence visible. Early observations can move the average substantially. Later observations usually create smaller changes.

Central limit theorem

The central limit theorem concerns repeated sample statistics. Sample means often approach a normal distribution. This occurs even when the original population is not normal.

The sampling distribution mode demonstrates this behavior directly. It generates many independent samples from one population. The selected statistic is calculated for every sample.

Monte Carlo simulation

Monte Carlo methods estimate quantities through repeated random experiments. They support risk, reliability, finance, queues, and scientific models. Complex systems often become manageable through simulation.

Probability estimates use the proportion of matching outcomes. Expected payoffs use the average simulated payoff. Uncertainty shrinks when more independent simulations are used.

Custom discrete distributions

A custom discrete model uses user-defined outcomes and probabilities. Every value needs a matching nonnegative probability. The probability total should equal one.

Automatic normalization accepts proportional weights instead. For example, weights two, three, and five become probabilities. They convert into 0.2, 0.3, and 0.5.

Custom continuous distributions

A custom continuous model uses a density expression. The density must remain nonnegative within supplied bounds. A reliable upper density limit is also required.

This calculator uses rejection sampling for custom densities. Candidate values are generated uniformly across the bounds. Candidates are accepted according to relative density height.

Incorrect density maxima can invalidate rejection sampling. The calculator checks sampled points for obvious violations. Complex densities may require careful manual verification.

Transforming random variables

A transformation creates a new variable from each sample. Linear transformations shift or rescale generated values. Nonlinear transformations can change skewness and support.

Examples include 2*x+5, x^2, sqrt(x), and log(x). The safe expression parser restricts available operations. Arbitrary PHP code cannot execute through this field.

Multiple random variables

Many practical systems contain dependent random variables. Correlation measures their linear relationship. Covariance also reflects joint movement and measurement scales.

The multivariable mode creates paired normal variables. Users control both means and standard deviations. They also choose a target correlation coefficient.

Distribution fitting

Distribution fitting estimates parameters from observed data. This calculator compares normal, exponential, Poisson, and lognormal models. Availability depends on the imported values.

Log-likelihood measures model support for observed values. AIC adds a penalty for parameter count. BIC applies a stronger sample-size-sensitive complexity penalty.

Lower AIC and BIC values are preferred comparatively. They do not prove that a model is correct. Visual diagnostics and subject knowledge still matter.

Histograms and empirical distributions

A histogram groups observations into numeric intervals. Its appearance depends on the selected bin count. Too few bins can hide important structure.

The empirical cumulative distribution shows observed cumulative proportions. It does not assume a theoretical model. Each step corresponds to one or more observations.

Normal Q-Q plots

A Q-Q plot compares observed and normal theoretical quantiles. Roughly linear points suggest approximate normal behavior. Curved patterns may reveal skewness or heavy tails.

Q-Q plots are exploratory rather than definitive. Large datasets can reveal small harmless deviations. Small datasets may hide meaningful non-normal behavior.

Skewness and kurtosis

Skewness describes distribution asymmetry. Positive skewness indicates a longer right tail. Negative skewness indicates a longer left tail.

Excess kurtosis compares tail behavior against a normal model. A normal distribution has zero excess kurtosis. Positive values often suggest heavier tails.

Confidence intervals

The displayed confidence interval estimates uncertainty around the sample mean. It uses the sample standard error. A normal critical value supplies the interval multiplier.

This interval is an approximation. Strong dependence can make it misleading. Very heavy tails can also reduce reliability.

Simulation limits

Every simulation contains Monte Carlo sampling error. Rare events may need extremely large sample sizes. Extreme-tail estimates can remain unstable.

Large calculations also consume memory and processing time. This application enforces sample-size and batch limits. Those safeguards reduce server exhaustion risks.

Distribution guide

DistributionTypical purposeMain parametersSupport
BernoulliOne success or failureSuccess probability0 and 1
BinomialSuccess count across trialsTrials and probability0 through n
GeometricTrials until first successSuccess probabilityPositive integers
Negative binomialFailures before required successesSuccesses and probabilityNonnegative integers
PoissonEvent countsAverage event rateNonnegative integers
HypergeometricSampling without replacementPopulation, successes, drawsFeasible counts
UniformEqual density across an intervalMinimum and maximumFinite interval
NormalSymmetric measurementsMean and standard deviationAll real numbers
LognormalPositive multiplicative dataLog-mean and log-SDPositive values
ExponentialWaiting timesRateNonnegative values
GammaPositive skewed durationsShape and scalePositive values
BetaProbabilities and proportionsTwo shape valuesZero through one
WeibullLifetime and reliabilityShape and scaleNonnegative values
Chi-squareVariance-related statisticsDegrees of freedomNonnegative values
Student tHeavy-tailed symmetric dataDegrees of freedomAll real numbers
F distributionVariance ratiosTwo degrees of freedomNonnegative values
CauchyVery heavy-tailed outcomesLocation and scaleAll real numbers
LogisticSymmetric heavier-tailed dataLocation and scaleAll real numbers
LaplaceSharp central peakLocation and scaleAll real numbers
ParetoHeavy-tailed sizes and lossesShape and minimumAbove minimum
RayleighVector magnitude modelsScaleNonnegative values
TriangularBounded expert estimatesMinimum, mode, maximumFinite interval

Practical simulation examples

ScenarioSuggested modelExample setupUseful output
Coin tossBernoullip = 0.5Success proportion
Six-sided dieDiscrete uniformMinimum 1, maximum 6Frequency balance
Defects in productionBinomialn = 100, p = 0.02Defect count risk
Customer arrivalsPoissonλ = 8 hourlyQueue planning
First sale timingGeometricp = 0.1Required attempts
Call waiting timeExponentialrate = 0.25Service thresholds
Exam scoresNormalmean 75, SD 10Percentiles
Machine lifetimeWeibullshape 1.8, scale 1000Failure probability
Claim severityLognormallog-mean 7.2, log-SD 0.8Tail loss
Website conversionsBinomialn = 1000, p = 0.04Conversion uncertainty
Portfolio shockStudent tdf = 5Heavy-tail stress
Market concentrationParetoshape 3, minimum 1Extreme-size behavior

Frequently asked questions

Does the same seed always produce identical results?

Identical inputs and seeds reproduce the same PHP pseudorandom sequence. Different PHP implementations may occasionally behave differently. Save the full configuration with the seed.

How many observations should I generate?

Hundreds work for basic demonstrations. Thousands usually produce steadier descriptive statistics. Rare-event analysis may require far larger simulations.

Why does the sample mean differ from expectation?

Random samples naturally fluctuate around theoretical expectations. The difference is called sampling error. It generally becomes smaller with larger samples.

What is the difference between PMF and PDF?

A PMF assigns probability to discrete outcomes. A PDF assigns density across continuous values. Continuous point probabilities are normally zero.

Can custom probabilities be unnormalized weights?

Yes, enable automatic normalization. The calculator divides every weight by their total. Negative weights remain invalid.

How should I choose a custom density maximum?

Use a value at least as large as the density's highest point. A value too small invalidates rejection sampling. An overly large value reduces efficiency.

Why can the Cauchy mean look unstable?

The theoretical Cauchy mean does not exist. Sample averages can shift dramatically with extreme observations. Increasing sample size does not ensure convergence.

What does coefficient of variation mean?

It divides standard deviation by the absolute mean. It expresses relative variability across comparable positive-scale measurements. Values near zero means need caution.

What does a high positive skewness indicate?

It suggests a longer or heavier right tail. A few large values may strongly affect averages. Medians may better represent central tendency.

What does the Q-Q plot show?

It compares sample quantiles against normal theoretical quantiles. Straight patterns support approximate normality. Curvature reveals skewness or tail differences.

Can this replace specialist statistical software?

It is suitable for learning and exploratory simulation. Critical research requires validated specialist methods. Always verify assumptions and numerical accuracy.

Can I simulate correlated non-normal variables?

The included multivariable mode currently generates correlated normal variables. General copula support requires additional dependence models. The single-file architecture can be extended.

Why are only some probability formulas supported?

Closed forms are implemented for widely used distributions. Other cases may require numerical integration. Simulation can estimate unsupported probabilities.

How are CSV values protected?

Generated values are numeric and written using PHP CSV handling. Uploaded text is never copied directly into exported formula cells. This reduces spreadsheet injection risks.

What security protections are included?

The form uses a CSRF token. User output is HTML escaped. Custom mathematics uses a restricted parser instead of eval.

Related Calculators

Average Calculator StatisticsGeometric Mean CalculatorInter Quartile Range CalculatorLower Quartile CalculatorMaximum CalculatorMean Calculator StatisticsMedian Calculator StatisticsMidhinge Calculator StatisticsMid Range Calculator StatisticsMode Calculator Statistics

Important Note: All the Calculators listed in this site are for educational purpose only and we do not guarentee the accuracy of results. Please do consult with other sources as well.