Course outline

R Programming / Evaluation, ownership, and reproducible results / Lesson 21

Design reproducible simulation checks

Control random inputs, record environment assumptions, and check a simulation against a simple analytical fixture.

About 19 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Separate repeatability from statistical validity.
  • Control random state and document its scope.
  • Use numerical tolerance and known fixtures in verification.
  • Design repeatability and validity checks as separate claims.
  • Record random-state context and quantify simulation uncertainty.

Define the claim

A reproducible simulation allows another analyst to rerun a specified procedure with controlled inputs and understand its environment. A fixed seed helps repeat random draws, but does not prove the model or sampling design is appropriate. State the population, parameter choices, number of draws, and intended estimate. Keep a simple case with a known answer so that a repeatable implementation can still be checked for conceptual and coding mistakes.

Control random state deliberately

The first function sets a seed and computes the mean of uniform draws. Two calls with the same arguments in the same environment should agree, and all.equal checks numerical equality. Setting the seed inside the function also changes the session’s random state; document that side effect or design a broader state-management policy. Validate seed and sample size according to the public contract before exposing this function in a production analysis.

r Repeat a seeded simulation
simulate_mean <- function(seed, n) {
  stopifnot(length(n) == 1L, !is.na(n), n > 0, n == as.integer(n))
  set.seed(seed)
  mean(runif(n))
}
first <- simulate_mean(42, 100)
second <- simulate_mean(42, 100)
isTRUE(all.equal(first, second))

The seed controls random draws in this environment; the function also changes session random state.

Check a known result

The second block compares mean with an explicit sum divided by length for a small fixed vector. This is a deterministic arithmetic check, not a proof that a simulation is statistically correct. A tolerance can accommodate justified floating-point differences; choose it based on the calculation and scale rather than accepting arbitrary disagreement. For a real simulation, also compare a known theoretical expectation and assess uncertainty across independent runs.

r Check a fixed arithmetic fixture
x <- c(1, 2, 3, 4)
expected <- sum(x) / length(x)
observed <- mean(x)
stopifnot(isTRUE(all.equal(observed, expected, tolerance = 1e-12)))

The deterministic check compares equivalent arithmetic with an explicit tolerance.

Record provenance and limitations

Record input data identity, code revision, R and package environment, random-number settings, and relevant configuration alongside the result. Avoid embedding private source data or credentials in shared artifacts. A seed without the algorithm, inputs, and environment is incomplete provenance. When a package or R behavior changes, rerun validation and explain meaningful differences instead of silently overwriting an earlier report.

Verify in a clean session

Run the script from its documented entry point in a clean session using controlled input and a fixed seed. Compare intermediate values and final output to the expected fixture, with a stated tolerance for numeric comparisons. Test invalid sample sizes and a deliberate change to the seed. Then inspect whether uncertainty and model assumptions are reported; repeated identical output alone is not evidence of an unbiased or valid estimate.

Separate repeatability from statistical validity

A reproducible simulation specifies a probability model, inputs, algorithm, random-state policy and execution context well enough to repeat or assess a result. It does not automatically establish that the model describes a real population, that the estimator is unbiased, or that the random draws are independent. Define the estimand and one replication before writing the loop. For a Bernoulli event with probability p, a hit indicator is one for the event and zero otherwise; the sample mean of independent indicators estimates p under the declared model.

A seed selects an initial generator state, not a complete experiment. R version, RNG kind, sampling algorithm, random-call order and data state can affect the resulting stream. Resetting the same seed before the same call under unchanged settings supports a within-session repeatability check; exact values are not promised across arbitrary versions or platforms. Resetting that seed inside every replication can repeat a stream prefix instead of creating independent replications. Document whether common random numbers are deliberate or accidental.

Connect a seeded run to an exact case

The illustrative function validates a positive whole-number replication count n and probability p between zero and one, then sets a seed and generates n Bernoulli draws using rbinom(n,size=1,prob=p). It returns the requested count, number of hits and their mean. With p=0.25 the exact probability for one success in one trial is dbinom(1,size=1,prob=0.25)=0.25. Two identical calls reset the seed and should produce identical returned records within the same generator configuration; this is a reproducibility property, not a claim that the estimated proportion equals 0.25.

The function intentionally changes the session random state by calling set.seed and drawing; its interface must document that side effect or be isolated in a controlled session. Seed validation and bounds appropriate to a public API need to be added separately. R and Rscript were unavailable during authoring, so the program, exact function call and repeatability assertion were not executed in R. The probability 0.25 is analytically known; no sampled sequence, observed estimate, standard error or benchmark is claimed.

r Illustrative synthetic simulation; unexecuted
simulate <- function(seed,n,p) {
  stopifnot(length(n)==1L,is.numeric(n),is.finite(n),n>0,n==floor(n),
            length(p)==1L,is.numeric(p),is.finite(p),p>=0,p<=1)
  set.seed(seed)
  draws <- rbinom(n,size=1,prob=p)
  list(n=n,hits=sum(draws),estimate=mean(draws))
}
exact <- dbinom(1,size=1,prob=0.25)
first <- simulate(42,100,0.25)
second <- simulate(42,100,0.25)
identical(first,second)
exact

The function validates replications, sets a seed and compares its Bernoulli interface with a known probability.

Build deterministic and statistical checks separately

Use a fixed trace to verify computation independent of random generation. For indicators 1,0,1,0 the hit count is 2 and the mean is 0.5. This tests the aggregation interface but cannot verify that draws follow the intended distribution. An exact small model supplies another check: two independent fair binary trials have probabilities 1/4,1/2,1/4 for zero, one and two successes. Compare simulated estimates with such a reference using an uncertainty-aware rule, not an assertion that every finite run must equal the exact probability.

For independent Bernoulli replications, the standard deviation of the estimated hit fraction is sqrt(p(1-p)/N) under the model. A plug-in estimate substitutes the observed hit fraction, but zero observed hits produce a zero plug-in value and do not prove the event impossible. Dependence, adaptive stopping and rare events require additional analysis. Report requested, valid and failed replications and define the treatment of failures; excluding them can change the estimand. More runs reduce Monte Carlo noise under suitable assumptions but do not repair a wrong model.

Test input and numeric boundaries

Validate n as one finite positive integer within a practical resource bound; reject zero, negative, missing, fractional or overly large requests according to the public contract. Validate probability, seed and any data dependencies separately. Test n=1 as a boundary and ensure each returned indicator is in the permitted set. The code should return an explicit failure or signal an appropriate condition for invalid input, rather than an empty mean or silent coercion. A controlled fixed trace can test expected output without depending on random values.

Floating-point results can differ slightly even for equivalent calculations. Choose a numerical tolerance appropriate to scale, algorithm and downstream decision, and compare identifiers, counts and schema exactly. isTRUE(all.equal(actual,expected,tolerance=...)) is one R pattern for an approximate check; the chosen tolerance is not a universal guarantee. If an estimate is near a decision threshold, test whether permitted error can alter the decision. A successful numeric comparison does not validate assumptions, sampling or data provenance.

Record and replay a bounded experiment

A useful record contains code revision, model and parameter choices, input provenance, R and package versions, platform, RNG configuration, seed, call sequence, sample size, failure policy and comparison criteria. Do not include credentials or private source records in a shared teaching artifact. Preserve the exact analytical fixture and expected invariants so a later reviewer can distinguish an implementation error from ordinary Monte Carlo variation or an environmental change.

In an actual supported environment, run from a clean session with controlled synthetic inputs and check deterministic fixtures, input boundaries, repeated-seed behavior and independent-run uncertainty. Capture warnings and failures rather than silently dropping them. Report the number of runs, estimated uncertainty and any untested compatibility boundaries. Changing a seed may change results but does not guarantee a different output for a discrete or rounded statistic; test state policy and statistical behavior instead of asserting inequality for every seed pair.

20 worked examples

1. Fixed hit trace

Problem: Compute the hit count and mean for fixed indicators 1,0,1,0.

  1. Two of the four indicators are one.
  2. Dividing two hits by four observations gives 0.5.
r Illustrative synthetic example; unexecuted
hits <- c(1,0,1,0)
c(count=sum(hits),mean=mean(hits))

Expected result: Count 2 and mean 0.5.

Why this result follows: A deterministic trace checks aggregation without testing the random generator.

2. Fair exact distribution

Problem: Enumerate success counts for two independent fair binary trials.

  1. The four ordered pairs are equally likely under the model.
  2. One has zero successes, two have one and one has two.
r Illustrative synthetic example; unexecuted
grid <- expand.grid(a=0:1,b=0:1)
table(factor(rowSums(grid),levels=0:2))/4

Expected result: Probabilities 0.25,0.5,0.25 for counts 0,1,2.

Why this result follows: Exact enumeration supplies a reference without Monte Carlo error.

3. Biased exact case

Problem: Find the probability of one success in one Bernoulli trial with p=0.3.

  1. A single Bernoulli trial has only success or failure.
  2. The model assigns success probability 0.3 directly.
r Illustrative synthetic example; unexecuted
dbinom(1,size=1,prob=0.3)

Expected result: 0.3.

Why this result follows: The exact distribution gives a known simulation target.

4. Repeat a seeded draw

Problem: Compare two identical sampling calls after the same seed reset.

  1. Each call begins after the same seed reset.
  2. The same sampling operation consumes the same stream in that configuration.
r Illustrative synthetic example; unexecuted
set.seed(31); a <- sample.int(6,5,replace=TRUE)
set.seed(31); b <- sample.int(6,5,replace=TRUE)
identical(a,b)

Expected result: TRUE under the same session and generator configuration.

Why this result follows: The check concerns repeatability within a stated environment.

5. Different seeds may coincide

Problem: Explain why two seeds may yield the same single Bernoulli result.

  1. Each seed leads to one outcome from the same two-value set.
  2. Different seeds can therefore produce the same observed indicator.
r Illustrative synthetic example; unexecuted
possible <- c(0,1)
length(possible)

Expected result: There are only two possible single-draw outputs.

Why this result follows: A seed change does not guarantee unequal discrete output.

6. Random-state side effect

Problem: Identify the effect of setting a seed inside a simulation function.

  1. set.seed establishes a new state in the session.
  2. runif consumes a draw and advances that state.
r Illustrative synthetic example; unexecuted
simulate <- function() { set.seed(5); runif(1) }
# Calling simulate() sets and advances session random state.

Expected result: The function sets and advances the session random state.

Why this result follows: The side effect should be documented or isolated.

7. Seed reset inside loop

Problem: Explain three repeated draws when each iteration resets seed 4.

  1. Every iteration starts from the same seed state.
  2. The same first sampling operation repeats the same result.
r Illustrative synthetic example; unexecuted
draws <- replicate(3,{set.seed(4);sample.int(10,1)})
length(unique(draws))

Expected result: 1 under an unchanged generator configuration.

Why this result follows: The loop repeats a prefix rather than independent advancing draws.

8. Record generator configuration

Problem: Capture R version and RNG kinds for an experiment record.

  1. The version identifies the running R environment.
  2. RNGkind reports the selected random-generator configuration.
r Illustrative synthetic example; unexecuted
record <- list(version=R.version.string,rng=RNGkind())
record

Expected result: The record contains the session version and generator kinds.

Why this result follows: These settings complement a seed and call-order record.

9. Validate sample size

Problem: Reject fractional replication count 2.5 under a positive-integer contract.

  1. The value is finite and positive.
  2. It differs from its floor and is therefore not a whole count.
r Illustrative synthetic example; unexecuted
n <- 2.5
valid <- length(n)==1L && is.finite(n) && n>0 && n==floor(n)
valid

Expected result: FALSE.

Why this result follows: Explicit validation prevents silent conversion of an invalid request.

10. Independence is a model assumption

Problem: Compare two identical stored indicators with two independently generated trials.

  1. Both entries were constructed from the same fixed value.
  2. Their identity does not demonstrate independent random generation.
r Illustrative synthetic example; unexecuted
copied <- rep(1,2)
copied

Expected result: The copied trace is 1,1 and contains one repeated value.

Why this result follows: Independence follows the design, not vector length.

11. Estimate from fixed hits

Problem: Calculate an event estimate from 30 hits in 100 supplied replications.

  1. The numerator counts 30 observed event indicators.
  2. Dividing by all 100 valid replications gives 0.3.
r Illustrative synthetic example; unexecuted
hits <- 30; n <- 100
hits/n

Expected result: 0.3.

Why this result follows: The estimate is the observed hit fraction for this trace.

12. Monte Carlo uncertainty

Problem: Compute plug-in standard error for estimate 0.25 over 100 independent replications.

  1. The estimated variance of the hit fraction is 0.25×0.75/100=0.001875.
  2. Taking the square root of that variance gives approximately 0.0433.
r Illustrative synthetic example; unexecuted
p_hat <- 0.25; n <- 100
sqrt(p_hat*(1-p_hat)/n)

Expected result: Approximately 0.0433.

Why this result follows: The calculation describes simulation variation under independent Bernoulli assumptions.

13. Zero hits do not prove impossibility

Problem: Interpret zero observed hits in 50 valid replications.

  1. No hit occurred in this finite trace.
  2. A small positive event probability can still yield a zero-hit run.
r Illustrative synthetic example; unexecuted
hits <- 0; n <- 50
hits/n

Expected result: The observed fraction is 0, not proof that the true probability is 0.

Why this result follows: Observed absence is not an impossibility proof.

14. Tolerance for arithmetic

Problem: Compare a computed value 0.3000000001 with 0.3 under tolerance 1e-6.

  1. The difference is approximately 1e-10 at this scale.
  2. It is smaller than the stated tolerance 1e-6.
r Illustrative synthetic example; unexecuted
actual <- 0.3000000001
isTRUE(all.equal(actual,0.3,tolerance=1e-6))

Expected result: TRUE under the specified comparison.

Why this result follows: The tolerance needs justification for the calculation and decision.

15. Exact count invariant

Problem: Check that four binary indicators sum to an integer between zero and four.

  1. The supplied trace contains three ones.
  2. Three lies within the valid count range zero through four.
r Illustrative synthetic example; unexecuted
draws <- c(1L,0L,1L,1L)
hits <- sum(draws)
hits>=0 && hits<=length(draws)

Expected result: TRUE; hits=3.

Why this result follows: A deterministic bound checks a basic output invariant.

16. Input provenance

Problem: Record a synthetic input identifier and model parameter.

  1. The input label distinguishes this fixture from another data source.
  2. The parameters describe the declared simulation request.
r Illustrative synthetic example; unexecuted
record <- list(input="synthetic-v1",p=0.4,n=100)
record

Expected result: The record identifies synthetic-v1, p=0.4 and n=100.

Why this result follows: Provenance connects results to controlled inputs and settings.

17. Random call order

Problem: Explain how an extra random call can alter a later draw.

  1. set.seed initializes the generator before either call.
  2. The first runif consumes randomness and advances the state used by the second.
r Illustrative synthetic example; unexecuted
set.seed(9)
first <- runif(1)
second <- runif(1)
# The second call uses the advanced stream state.

Expected result: The second call uses the state after the first draw.

Why this result follows: Call order is part of a reproducibility record.

18. Stream policy

Problem: Distinguish deliberate shared random numbers from accidental repeated seeds.

  1. Shared draws can be deliberately used to compare alternatives on common inputs.
  2. Independent replications require an appropriate separate stream design rather than identical resets.
r Illustrative synthetic example; unexecuted
policy <- list(shared_stream="deliberate comparison",independent="separate replication design")
policy

Expected result: The two policies state different purposes.

Why this result follows: Stream ownership must match the comparison and uncertainty calculation.

19. Report failed replications

Problem: Summarize 90 valid and 10 failed replications with 27 valid hits.

  1. The valid and failed counts sum to 100 requested runs.
  2. The valid-only hit fraction is 27/90=0.3.
r Illustrative synthetic example; unexecuted
valid <- 90; failed <- 10; hits <- 27
list(requested=valid+failed,valid=valid,failed=failed,estimate=hits/valid)

Expected result: Requested 100, valid 90, failed 10, valid-only estimate 0.3.

Why this result follows: Reporting failures exposes the denominator and possible selection effects.

20. Bias of a repeatable estimator

Problem: Find the model bias of estimator twice the sample hit mean when p=0.4.

  1. The sample hit mean has expectation 0.4 under the Bernoulli model.
  2. Multiplying by two gives expectation 0.8, which exceeds the target by 0.4.
r Illustrative synthetic example; unexecuted
p <- 0.4
expected_estimator <- 2*p
bias <- expected_estimator-p
c(expected=expected_estimator,bias=bias)

The fixture computes the estimator expectation and bias from the stated model probability.

Expected result: Expected estimator=0.8; bias=0.4.

Why this result follows: A fixed seed can repeat an estimator whose expectation differs from its target.

Common errors and fixes

A repeatable result is presented as proof of validity

Why it happens
A fixed seed was confused with a correct model and representative inputs.
How to fix it
Review the model and compare with known cases and uncertainty.
Prevent it next time
Document assumptions and validate the design independently of repeatability.

A later analysis gets unexpected random draws

Why it happens
The function changed the session random state without documenting it.
How to fix it
Define and document random-state ownership or isolate the analysis session.
Prevent it next time
Test interactions with other random operations in a clean session.

A fragile equality check fails on tiny numeric differences

Why it happens
Floating-point values were compared without a justified tolerance.
How to fix it
Use an appropriate numerical comparison for the calculation.
Prevent it next time
Test a known fixture and document the selected tolerance.

20 practice exercises

1. Does setting the same seed establish that a simulation is unbiased?

Show hint

Separate a reproducible stream from estimator behavior.

Show worked solution

No. It helps repeat the random sequence in the stated environment, but bias depends on the model, sampling, and estimator. Compare with known cases and report uncertainty.

The same seed can reproduce a sequence under a fixed environment but cannot establish unbiasedness. Bias depends on the estimator and model; compare with known cases and assess uncertainty independently.

Check your solution

  • Repeatability is tied to configuration.
  • Bias is not established by the seed.

2. Why compare with a tolerance?

Show hint

Consider rounding at the scale of the calculation.

Show worked solution

Floating-point calculations can differ slightly despite representing the same intended result. Select a tolerance appropriate to the scale and computation, and investigate differences larger than that threshold.

Floating-point calculations can differ slightly despite the same mathematical target. Choose and document a tolerance justified by the units and decision, and investigate larger differences rather than using one universal value.

Check your solution

  • The tolerance matches the stated quantity.
  • Differences outside the bound are investigated.

3. A simulator claims P(X>=1)=0.9 for two independent Bernoulli trials with p=0.2. Diagnose the exact reference.

Show hint

Compute the probability of no successes first.

Show worked solution

The no-success probability is 0.8²=0.64, so at least one success has probability 0.36. The claimed 0.9 conflicts with the model and should fail the deterministic reference check.

Check your solution

  • The no-success probability is 0.64.
  • The exact target is 0.36.

4. A Bernoulli generator is requested for five trials at p=0 and p=1. Specify deterministic boundary checks.

Show hint

At the two probability endpoints every outcome is fixed by the model.

Show worked solution

At p=0 all five indicators must be zero; at p=1 all five must be one. These boundary checks test output support and parameter handling, but do not prove correctness for intermediate probabilities.

Check your solution

  • The p=0 result has zero hits.
  • The p=1 result has five hits.

5. Two saved simulation records have identical outputs but different code revisions. Design a reproducibility audit before declaring a match.

Show hint

Compare configuration and implementation as well as values.

Show worked solution

Compare code revision, input identity, generator settings, seed and ordered random calls, then rerun a known fixture. Matching output alone may be coincidental or conceal a changed algorithm.

Check your solution

  • The revisions are compared.
  • A known fixture is rerun.

6. A developer proposes distinct deterministic seeds 1 through 100 as proof of independent replications. Diagnose the claim.

Show hint

Different seed labels do not by themselves prove stream independence.

Show worked solution

A sequence of different seeds is not itself a proof of independent streams or a justified uncertainty model. Specify and validate a generator and stream design, and document how replications are constructed.

Check your solution

  • Distinct seeds alone are insufficient evidence.
  • The stream design is documented.

7. A simulation must leave the caller’s random stream unchanged. Propose a safe test boundary for its documented state policy.

Show hint

Compare a control sequence with the sequence after the isolated call.

Show worked solution

Run a control and the simulation in clean isolated sessions under the same documented initial state, then compare the caller sequence. The test must also cover a failed simulation call and record the generator configuration.

Check your solution

  • A control sequence is compared.
  • The error path is included.

8. A reproducibility record has seed and RNG kind but omits the simulation input and call order. Identify two consequences.

Show hint

The same stream can be applied to different computations.

Show worked solution

Different inputs can change the target, and reordered random calls can send different draws to each operation. Record input identity and ordered calls before claiming the record is sufficient.

Check your solution

  • Input identity is missing.
  • Random-call order is missing.

9. A simulator receives n=c(4,5), p=1.2 and a maximum of 1000 runs. Identify every violated input rule.

Show hint

Check scalar length and probability range independently.

Show worked solution

The count has length two rather than one, and p=1.2 lies outside [0,1]. Reject both violations before drawing; the resource bound does not repair either invalid field.

Check your solution

  • The count is not scalar.
  • The probability exceeds one.

10. A fixed binary trace contains an invalid value 2 among 0,1,2,1. Design an invariant check before estimating probability.

Show hint

Every indicator must belong to the set {0,1}.

Show worked solution

Reject the trace because 2 is not a Bernoulli indicator. Check all(draws %in% c(0,1)) before averaging; reporting its mean as a hit fraction would misstate the data.

Check your solution

  • The value 2 is invalid.
  • No hit estimate is accepted.

11. A Bernoulli simulation with true model probability 0.1 has zero hits in 100 runs. Compare the plug-in standard error with the model standard deviation.

Show hint

Substitute the observed estimate and then the stated model probability separately.

Show worked solution

The observed estimate is 0, giving plug-in standard error 0. The model standard deviation is sqrt(0.1×0.9/100)=0.03; the zero plug-in value does not establish certainty or impossibility.

Check your solution

  • The plug-in standard error is 0.
  • The model standard deviation is 0.03.

12. For independent runs with event probability 0.01, calculate the model probability of zero hits in 100 runs.

Show hint

Each run misses with probability 0.99.

Show worked solution

Independence gives 0.99^100, approximately 0.366. A zero-hit sample is therefore quite possible under this positive-probability model; this is a model calculation, not an observed run.

Check your solution

  • The per-run miss probability is 0.99.
  • The zero-hit probability is approximately 0.366.

13. An estimated value 0.4999 is within 0.001 of 0.5, but a decision uses the threshold 0.5. Diagnose equivalence.

Show hint

Numerical closeness and the decision boundary are distinct.

Show worked solution

The absolute difference 0.0001 passes the stated tolerance, yet 0.4999 is below the threshold and 0.5 meets it under a >= rule. Test the decision separately before calling the results equivalent.

Check your solution

  • The numeric tolerance passes.
  • The two threshold decisions differ.

14. A result has expected IDs a,b but actual IDs b,a and nearly equal numeric values. What must be checked exactly?

Show hint

Identity and numeric tolerance address different properties.

Show worked solution

Compare the ordered IDs exactly; the reversed order fails even if numeric values are close. Restore verified alignment before applying an appropriate numeric tolerance to corresponding values.

Check your solution

  • The ordered ID check fails.
  • Numeric tolerance cannot excuse reordered IDs.

15. A test asserts that changing seed always changes the rounded mean of ten binary draws. Give a counterexample and a better assertion.

Show hint

Different streams can produce the same rounded statistic.

Show worked solution

Two different sequences can have the same number of hits, so their rounded means can coincide. Test documented repeatability for a fixed configuration and assess variation across multiple runs without requiring every pair to differ.

Check your solution

  • Equal rounded means are possible.
  • The test does not assert universal inequality.

16. Input IDs A,B have event probabilities 0.1,0.9, but a pipeline swaps those probabilities. Why can a mean-only check miss the defect?

Show hint

The average remains unchanged when values are swapped.

Show worked solution

Both assignments average to 0.5, but A and B receive each other’s probabilities. Verify each ID-probability association and source order; a stable aggregate does not establish correct pairing.

Check your solution

  • The mean is 0.5 in both assignments.
  • Both ID-probability associations change.

17. A comparison deliberately uses common random inputs for two methods. Why must its uncertainty analysis account for pairing?

Show hint

The method results share random inputs.

Show worked solution

The two results are dependent because they use the same random inputs. Analyze the paired differences or another justified comparison design rather than treating the results as independent by default.

Check your solution

  • The methods share inputs.
  • The uncertainty calculation accounts for dependence.

18. A failed replication is omitted, and failures are more likely for large outputs. Explain the bias risk and required report.

Show hint

Failure is related to the quantity being estimated.

Show worked solution

Excluding failures preferentially removes large outcomes and can lower the valid-only estimate. Report requested, valid and failed counts, the failure mechanism and the target affected by this selection.

Check your solution

  • The failure mechanism is nonrandom.
  • The valid-only estimate may be biased downward.

19. List a reproducibility record for a 100-run Bernoulli simulation with p=0.2 and seed 5.

Show hint

Include model, code, input, random state and environment.

Show worked solution

Record p=0.2, n=100, seed 5, code revision, R version, RNG kinds, call order, input identity and failure policy. State expected checks and distinguish observed results from theoretical targets.

Check your solution

  • The parameters and seed are recorded.
  • The environment and call order are recorded.

20. A simulator of three fair independent trials estimates P(exactly two successes) as 0.38. Compare with its exact target using absolute tolerance 0.02.

Show hint

There are three favorable triples out of eight.

Show worked solution

The exact target is 3/8=0.375, and the absolute difference is 0.005, so this particular 0.02 check passes. A single pass does not prove the generator or model valid.

Check your solution

  • The exact probability is 0.375.
  • The difference 0.005 is within 0.02.

Key takeaways

  • A seed supports repeatability but does not validate a model.
  • Record provenance and verify known results with justified tolerances.
  • A seed alone does not validate an estimator.
  • Exact fixtures and Monte Carlo checks have different roles.
  • Document random-state side effects and failure counts.

Official references