Random numbers support cryptography, simulations, games, statistical sampling and controlled scientific experiments. Yet a sequence that looks irregular to a person may be predictable, biased or repeated. Reliable random-bit generation therefore requires mathematics that separates unpredictability, distribution, independence, testing and construction.
This topic answers **why mathematics is important in computing and AI**. Probability defines what “random” means, entropy measures uncertainty under a model, statistical tests look for selected patterns, and algorithms expand secret state into reproducible pseudorandom sequences. The central lesson is wonderfully cautious: passing tests does not prove unpredictability.
Random, pseudorandom and unpredictable
A physical noise source may produce observations influenced by thermal, electronic or quantum processes. A deterministic random bit generator produces bits from an internal state using a defined algorithm. If the starting state is known, the sequence is reproducible by design.
NIST’s random-bit-generation framework separates entropy sources from deterministic mechanisms and constructions. SP 800-90B specifies requirements and validation tests for entropy sources; SP 800-90A addresses deterministic random bit generator mechanisms; SP 800-90C specifies constructions combining them.
These roles should not be collapsed into one word, “random”. A source can be noisy but biased. An algorithm can pass many statistical tests yet be predictable from its state. A secure construction needs more than visually balanced output.
The sample space comes first
For a fair bit, P(0)=P(1)=0.5. For a biased bit with P(1)=0.6, long sequences are expected to contain more ones, but any finite sequence can deviate by chance.
If n independent fair bits are produced, there are 2ⁿ possible length-n sequences, each with probability 2⁻ⁿ. Independence is an assumption about the joint distribution, not something proved because adjacent bits look different.
Expected count and variation
For n Bernoulli trials with success probability p, the count X of ones has expected value np and variance np(1−p). With n=1,000 and p=0.5, expected ones are 500 and standard deviation is √250 ≈ 15.81.
Seeing 520 ones is therefore not automatically alarming. It is about 1.26 standard deviations above the expectation in the independent fair-bit model. Seeing exactly 500 ones is not proof of randomness either; a deterministic generator could force that count.
Shannon entropy and min-entropy answer different questions
For outcomes with probabilities pi, Shannon entropy is:
**H = −Σ pi log2(pi)**
For a bit with probabilities 0.6 and 0.4:
**H ≈ −0.6log2(0.6) − 0.4log2(0.4) ≈ 0.971 bits**
Min-entropy focuses on the most likely outcome:
**Hmin = −log2(max pi) = −log2(0.6) ≈ 0.737 bits**
The two measures are not interchangeable. Min-entropy is conservative for guessing probability and is important in entropy-source assessment. An estimate is only as credible as the source model, sampling and assumptions.
Entropy rate and dependence
Even if individual bits are balanced, dependence can reduce uncertainty per bit. Consider the alternating sequence 010101… with a random first bit. Each position may appear balanced across repeated runs, yet once the first bit is known, the rest is predictable.
Entropy rate accounts for uncertainty added per new sample given the past. Health testing and source modelling therefore look beyond the proportion of ones.
Did You Know? Perfect balance can be perfectly predictable
A sequence containing exactly half zeros and half ones may have been created by a fixed recipe. Frequency balance is one property, not a certificate of randomness. This is why multiple tests and a design argument are both needed.
What a statistical test actually asks
A statistical test begins with a null model, computes a statistic and maps it to a p-value or decision rule. A small p-value indicates that the observed statistic would be unusual under that null model. It is not the probability that the generator is bad, nor the probability that the null is true.
If many tests are performed, some small p-values occur by chance. Test suites therefore require interpretation of both individual results and proportions across sequences. Selecting only passing runs after seeing results invalidates the assessment.
NIST SP 800-22 specifies statistical tests for random and pseudorandom generators used in cryptographic applications, while NIST’s current project page places those tests within a broader random-bit-generation framework. Statistical testing complements source analysis; it does not replace it.
Runs, autocorrelation and pattern tests
A runs test examines consecutive groups of identical bits. Too few runs may suggest persistence; too many may suggest alternation. Autocorrelation compares a sequence with shifted versions of itself.
Different tests target different departures from a model. Passing a frequency test says little about long-range dependence. Passing a runs test says little about knowledge of internal state. There is no finite test suite that proves an arbitrary sequence is unpredictable.
Pseudorandom generators and state
A simple linear congruential generator has the form:
**Xn+1 = (aXn + c) mod m**
It is useful for teaching modular arithmetic and recurrence, but parameter choices can create short periods and lattice structure. It should not be treated as a cryptographic generator merely because its output looks messy.
The state space limits the period. With at most m states in a deterministic recurrence, a state must eventually repeat, after which the future repeats. Cryptographic generators add security requirements about prediction and state compromise that elementary period analysis alone cannot provide.
Worked example: bias and guess probability
Suppose a fictional binary source produces one with estimated probability 0.55 and zero with 0.45, with independence assumed only for the example. The best single-symbol guess is “one”, succeeding with probability 0.55. Min-entropy is −log2(0.55) ≈ 0.862 bits per sample.
For two independent samples, the most likely pair “11” has probability 0.55² = 0.3025 and min-entropy −log2(0.3025) ≈ 1.724 bits. Without independence, simply multiplying per-sample entropy would not be justified.
Conditioning is not magic
A conditioning function can reduce bias and compress raw samples, producing output closer to a desired distribution. It cannot create more true uncertainty than enters the system. Output length must respect a defensible entropy estimate and the construction requirements.
Hashing a constant sequence may produce a complex-looking fixed value. Appearance changes; uncertainty does not. This is a powerful general lesson for data science: transformation cannot rescue missing information by declaration.
Which mathematics matters?
Probability
Distributions, conditional probability and independence define the claims. Without a probability model, “random” is only an impression.
Information theory
Shannon entropy, min-entropy and entropy rate quantify different aspects of uncertainty. Their assumptions must travel with the number.
Statistics
Hypothesis tests, confidence intervals and multiple-testing reasoning help detect selected departures from a model.
Number theory and algebra
Modular arithmetic drives many pseudorandom recurrences and cryptographic constructions. Period and state transition structure are algebraic questions.
Computing
Implementation, seeding, state protection, concurrency and failure handling matter. A sound algorithm can be weakened by poor integration.
Common misconceptions
- “It passed NIST tests, so it is secure” overstates what statistical tests prove.
- “Half zeros and half ones means random” ignores order and dependence.
- “Entropy equals noise amplitude” confuses physical variation with unpredictability.
- “Hashing adds entropy” mistakes redistribution for creation of uncertainty.
- “A long period guarantees security” ignores state recovery and prediction.
- “A p-value is the chance the generator is faulty” misinterprets hypothesis testing.
A responsible classroom investigation
Compare three sources: repeated coin tosses, a deliberately alternating sequence with one random starting bit, and output from a small recurrence. Use equal-length samples. Calculate proportion of ones, run counts and lag-one autocorrelation.
Students should predict which tests will distinguish the sources, keep raw sequences, state the null model and repeat the experiment. They should not use homemade generators to protect real information.
Parents can ask a wonderfully revealing question: if someone knew the method and everything observed so far, how well could they guess the next result? That shifts attention from visual messiness to conditional prediction.
Limits and current standards
NIST’s SP 800-90B page, checked 8 October 2026, notes identified errata and future revision work. This is a reminder that standards have editions and implementation guidance. Security work should use the current authoritative document set, validated components where required and specialist review.
This article does not recommend a generator for any application. Cryptographic key generation is high stakes; use platform-approved, well-maintained cryptographic interfaces rather than classroom code.
Frequently Asked Questions
Can a deterministic sequence be statistically random-looking?
Yes. Pseudorandom generators are designed to produce outputs with many statistical properties, yet the sequence is determined by algorithm and state.
Does more noise always mean more entropy?
No. Noise can be biased, correlated, influenced by environment or partly observable to an attacker. Entropy needs a source model and conservative estimation.
Why use min-entropy?
It relates to the probability of the most likely outcome and supports conservative reasoning about guessing. It is not a synonym for Shannon entropy.
What happens when many tests are run?
Some apparently significant outcomes occur by chance. Evaluation must account for the test plan, significance levels, number of sequences and expected pass proportions.
Is a coin toss truly random?
It can be modelled probabilistically for many purposes, but physical tosses may have bias or dependence. The adequacy of the model depends on the question and procedure.
Useful next reading
- NIST SP 800-90B: Entropy Sources Used for Random Bit Generation
- NIST SP 800-90C: Random Bit Generator Constructions
- NIST Random Bit Generation project
- NIST SP 800-22: Statistical Test Suite
- Why Mathematics? Bloom Filters, Hash Functions and False Positives
- Why Mathematics? Distributed Consensus, Quorums and Fault Tolerance
- Why Mathematics? Comparing Percentages Fairly
- Mathematics Learning Hub
Casebook: Testing Claims About Randomness
Case 1: A fair process can look unbalanced
Generate many independent length-1,000 fair-bit sequences and count ones. The counts should vary around 500 with standard deviation about 15.81, not land exactly on 500 every time. Students can plot a histogram and compare empirical spread with the binomial model. A single count of 520 is ordinary under that model, while a mechanism that forces exactly 500 ones in every block may be suspiciously constrained. This case corrects the intuition that visual balance proves randomness. The model assumes independent trials with constant probability; changing either assumption changes the expected distribution of counts.
Case 2: Marginal balance hides dependence
Construct a two-state process that tends to repeat its previous bit with probability 0.95 but begins equally likely at zero or one. Across a long run the marginal fraction may be near one half, yet long runs and positive lag-one correlation reveal dependence. The best next-bit guess uses the previous bit and succeeds far more often than 0.5. Compare its Shannon entropy per marginal symbol with its conditional entropy rate. This demonstrates why a balanced histogram does not imply fresh uncertainty at each sample. Source evaluation must examine temporal structure and conditions that might change it.
Case 3: The perfectly alternating trap
The sequence 010101… has equal zeros and ones and may pass a simple frequency check. Its runs count is extreme and, after the first bit, every next bit is known. Students should calculate lag-one correlation under a declared numeric mapping and compare it with a shuffled version. If the starting bit is random, the entire sequence contains at most one bit of uncertainty, not one bit per position. This memorable counterexample separates marginal distribution from joint distribution. It also shows why test suites contain complementary tests rather than one universal score.
Case 4: Understanding an occasional small p-value
Under a correctly specified null model, p-values are approximately uniform when assumptions and test calibration hold. Running 100 independent tests at a five-percent threshold therefore produces about five rejections on average, though the actual number varies. Students can simulate this distribution and see that one small p-value is not proof of a broken generator. Conversely, choosing only the sequences that pass after inspection biases the evidence. A test plan should predeclare statistics, thresholds, sample sizes and treatment of multiple comparisons. The interpretation must consider both individual failures and patterns across many sequences.
Case 5: A small recurrence reveals finite state
Choose a tiny linear congruential recurrence and enumerate states until one repeats. Once a state recurs, the future repeats because the update is deterministic. Different parameters and seeds may enter different cycles or have different periods. Plot successive pairs to reveal structure that a one-dimensional histogram may hide. The exercise is useful for modular arithmetic and state reasoning, but it does not assess cryptographic security. A long period is only one property; prediction resistance, state compromise behaviour, seeding and implementation are separate concerns.
Case 6: Entropy estimates depend on the model
For an independent biased bit with P(1)=0.55, min-entropy is about 0.862 bits per sample. If samples are correlated, multiplying that value by sample count may exaggerate uncertainty. Students can compare an independent source with a Markov source having the same marginal probability but high persistence. Estimate transition probabilities and the success rate of a predictor using the previous symbol. The example shows that per-symbol distribution does not define entropy rate by itself. Conservative source assessment must include operating conditions, data collection and assumptions about adversarial knowledge.
Case 7: Conditioning redistributes; it does not create
Apply a hash-like toy mixing function to a constant input, a two-choice input and a richer synthetic source. The outputs may all look complicated, but their number of possible values cannot exceed the number of possible inputs. If only two raw states are possible, an observer who knows the function faces only two conditioned candidates. Students can enumerate this small case exactly. Real conditioning can reduce bias and concentrate available entropy when used in a justified construction, yet output length and security claims must respect a conservative input estimate. Mathematics prevents visual complexity from being mistaken for new information.
Case 8: Health tests and full evaluation are different
An online repetition-count test might alarm when one symbol repeats too many times, catching a stuck or severely degraded source. Its threshold creates a trade-off between false alarms and missed failures. Passing the test does not estimate complete entropy or certify every distribution property. Students can simulate a healthy source, a stuck source and a subtly biased correlated source, then compare alarm rates. This case clarifies the role of continuous health monitoring within a larger design. Real cryptographic random-bit generation should follow current authoritative standards and validated platform mechanisms; a classroom detector is not a security control.
Case 9: Seeds, reproducibility and independence
Simulations often need reproducibility, so researchers record a pseudorandom seed. Reusing one seed is useful for debugging but does not show that a result is robust across generated samples. Students can repeat a Monte Carlo estimate with several recorded seeds and compare between-run variation with the estimator’s expected standard error. Starting parallel workers with related or identical state may create overlapping streams, so “four processes” does not automatically mean four independent samples. The lesson is not to invent a seeding scheme for security; it is to document state and understand how computational reproducibility differs from physical randomness.
Case 10: Randomness in sampling does not remove bias automatically
A random-number generator can select survey records or experimental units, but it cannot fix an incomplete sampling frame or non-response. Students can simulate a population containing two groups, omit part of one group from the frame and draw perfectly random samples. The estimates remain biased relative to the full population because the selection mechanism never reaches missing members. This example broadens the importance of mathematics: algorithmic randomness supports fair selection only within the defined frame. Probability calculations must travel with data-collection assumptions.
Case 11: Compression is not an entropy certificate
Highly regular sequences often compress well, encouraging the intuition that incompressibility means randomness. Yet a short sample may be incompressible for a chosen algorithm while still being generated predictably, and encrypted or pseudorandom data can be reproducible from state. Students can compare compression ratios for repeated, alternating, biased and generator-produced files, keeping length fixed. The result is one descriptive test tied to one compressor, not a proof of entropy. This case illustrates a recurring theme: every statistic detects particular structure and leaves other alternatives unresolved.
Case 12: Writing a defensible conclusion
“The generator is random because all tests passed” overclaims. A better classroom conclusion names the evaluated data, test set, sample sizes, thresholds and observed results, then states that no targeted departures were detected under those conditions. It separately describes the source model, min-entropy assumptions and construction if those were evaluated. It also notes that statistical results do not establish prediction resistance or secure implementation. This calibrated language may be longer, but it accurately separates evidence from inference. In security and science alike, precision about what was not shown is part of the mathematics.
A final perspective
Random-number generation teaches one of mathematics’ most useful forms of humility. Balance is not independence, passing tests is not proof, entropy is not a visual effect, and transformation cannot manufacture missing uncertainty. Mathematics makes these distinctions precise, allowing computing systems to replace “looks random” with a documented chain of source assumptions, conservative estimates, constructions and continuing health checks.
A Practical Investigation Studio
These investigations make the article auditable. Complete two or three for a short project or the full sequence as a portfolio. The purpose is to expose assumptions and error signals, not to imitate professional engineering, manufacturing, metrology or security certification.
Investigation 1: Coin baseline
Generate repeated synthetic fair-coin sequences and count ones. Compare observed variation with the binomial standard deviation. Use synthetic or openly released teaching data. Begin by naming the response variable, input variables, units and prediction before calculating. Preserve raw values and unrounded intermediates in a table, then make one graph whose axes communicate the model clearly. Add an independent hand estimate and a dimensional or limiting-case check. Deliberately introduce one unit error and describe the numerical signature rather than merely correcting it. Label every quantity observed, assumed, fitted or derived. Record the model domain and one condition that would require a richer model. Ask a peer to reproduce the result from the written procedure without seeing the answer. If the reproduction differs, locate whether the ambiguity arose in definitions, units, rounding or software defaults. End by explaining the result to a younger student in three sentences. This remains a classroom calculation, not professional validation or a safety, production or security decision.
Investigation 2: Balanced trap
Create a deterministic alternating sequence with exactly half ones. Show which frequency check it passes and which predictability check it fails. Create a data dictionary before entering a spreadsheet or script. State how each row was obtained, which values are exact by definition and which are measurements or simulated observations. Calculate once with full precision and once with premature rounding, then compare the final difference. Vary the principal input across at least five sensible values and look for linearity, curvature or instability instead of reporting only two endpoints. Keep signed residuals if a model is fitted, because absolute errors hide direction. Include a graph and a small results table that another person can audit. Write a one-paragraph uncertainty note distinguishing input uncertainty from model-form limitations. A peer should be able to reconstruct one row from the formula and raw data alone. State what evidence would falsify the interpretation. Do not present the exercise as a certified engineering, manufacturing, metrology or cryptographic assessment.
Investigation 3: Runs count
Count runs in fair, persistent and alternating fictional sequences. Predict too few or too many runs before computing. Treat the investigation as a comparison of hypotheses, not a hunt for an attractive number. Write a baseline model and at least one plausible alternative, then predict where their outputs should diverge. Hold all unrelated inputs fixed while varying the chosen factor. Preserve coordinate, sign, phase, size-weighting or bit conventions beside the data. Use a ratio, residual or normalised error that has a declared denominator. Repeat the calculation with that denominator changed and explain why the percentage changes. Check one extreme case where the answer should approach zero, unity or another known limit. Make the graph before writing the conclusion and note any outlier without deleting it. Separate repeatability of one prepared sample from coverage across positions, times or populations. The final claim should match the observed range and must not be extrapolated into real operational approval.
Investigation 4: Lag correlation
Calculate lag-one and lag-two autocorrelation for several binary sequences. State the bit-to-number mapping and denominator. Plan the computation so that errors leave visible fingerprints. Save the raw input, transformed input, intermediate result and final result in separate columns or variables. Insert one deliberate sign reversal, one missing observation and one hidden reset, each in a separate copy, and document how the plots or checks respond. Compare an analytical shortcut with the more complete calculation over a range where the shortcut is expected to fail. Report the largest absolute difference and where it occurs. Include conservation, balance, boundedness or monotonicity checks appropriate to the topic. If a fitted curve is used, inspect residual clusters and changing spread instead of relying on one fit statistic. Have a peer review only the assumptions first, then the arithmetic. Keep the conclusion educational and conditional on the fictional data.
Investigation 5: Entropy measures
Calculate Shannon and min-entropy for several biased alphabets. Explain why the values answer different questions. Build a sensitivity map rather than changing several settings at once. Choose a baseline, vary one input downward and upward, and express output change in both original units and a dimensionless ratio. Then select a second input and repeat. If interactions seem likely, test a small two-dimensional grid and identify where the one-factor interpretation breaks down. State why the chosen ranges are plausible for the teaching model. Preserve failed or surprising runs and annotate them. Compare computational resolution or sample length at three levels so numerical artefacts are not confused with physical behaviour. Provide a hand estimate for the order of magnitude. Finish with a decision table using cautious language—stable, sensitive or unresolved—rather than safe or unsafe. Classroom evidence cannot authorise a product, structure, process or security control.
Investigation 6: Dependent source
Construct a balanced Markov source with high persistence. Compare marginal balance with conditional next-bit guess probability. Make uncertainty visible at every stage. Assign each input a source and a plausible interval, then identify which inputs are correlated rather than automatically treating them as independent. Propagate uncertainty with a simple high-and-low calculation or transparent simulation, and retain the seed or full synthetic samples for reproduction. Compare the spread caused by measurement variation with the shift caused by changing the model assumption. Plot both if possible. Explain why more decimal places do not narrow an interval supported by weak inputs. If a result lies near a fictional decision boundary, rewrite the conclusion to reflect the chance of crossing it. Ask a peer to challenge the largest assumed uncertainty and rerun the analysis. Report the conclusion as evidence about the model, never as professional certification.
Investigation 7: LCG period
Enumerate a small linear congruential recurrence until a state repeats. Relate observed period to finite state space without claiming cryptographic security. Audit representation choices. Recalculate after changing the coordinate origin, phase wrapping convention, histogram bins, mesh labels or binary mapping while preserving the underlying situation. A correct physical or probabilistic conclusion should change only where the definition genuinely changes. Show one example where a visual choice exaggerates or hides a pattern. Use identical axes for fair comparison and include sample count or resolution in captions. Test an invariant such as total mass, probability, force, energy sign or average ratio. Where values are averaged, identify whether the mean is number-, mass-, volume-, time- or state-weighted. Ask another student to explain the plot without reading the conclusion; revise labels if their interpretation differs. The display supports reasoning but cannot replace domain review.
Investigation 8: P-value simulation
Generate null-model test statistics and examine the distribution of p-values. Show why occasional small values are expected across many tests. Separate verification from validation. First verify arithmetic or code against a case with a known answer, including units and at least one manually calculated row. Next ask whether the teaching model represents the intended phenomenon and list the omitted mechanisms. Refine numerical resolution or increase synthetic sample length and record whether the chosen quantity stabilises. A stable answer can still arise from an unrealistic model, so compare with an alternative assumption or openly documented benchmark. Record software version, solver or library settings and stopping rules. Avoid tuning settings after seeing the desired result; predeclare the comparison instead. Summarise numerical error, input uncertainty and model-form uncertainty separately. No classroom agreement with a benchmark should be described as product or system validation.
Investigation 9: Multiple tests
Apply three pre-declared checks to many teaching sequences. Record all results and prohibit discarding failed runs after inspection. Design the investigation to reveal dependence over position, time or sequence order. Keep the original ordering, then compare with a deliberately shuffled copy and explain which statistics change. Examine at least two lags, locations or neighbourhood scales rather than only the overall average. Plot local values alongside the aggregate so compensating errors are visible. State whether successive observations are plausibly independent and why that matters to the calculation. If repeated measurements share one specimen, source or initial state, do not count them as independent coverage. Add a block or subgroup analysis and note any drift. Preserve the random seed for simulated data but use more than one seed before generalising. The conclusion should describe detected structure without claiming causation from the pattern alone.
Investigation 10: Conditioning demo
Hash or mix a fixed low-entropy source in a toy example. Show that complicated-looking output does not create new source uncertainty. Create an adversarial edge-case test. Identify the smallest, largest, most symmetric and most irregular inputs allowed by the classroom model, predict the expected behaviour, and then compute it. Include zero or a limiting value only when mathematically meaningful. Watch for division by a small number, logarithms of invalid values, wrapped angles, negative geometry, impossible probabilities or solver singularities. Replace silent software errors with explicit checks and explanatory messages. Compare the edge cases with the ordinary baseline on the same scale and describe why a method that works in the middle may fail near a boundary. Record the first assumption that breaks. The exercise is about model literacy; it is not permission to explore hazardous physical extremes.
Investigation 11: Health check
Design an online repetition-count alarm for a fictional binary sensor. Discuss false alarms, missed failures and why a health test is not a full entropy estimate. Prepare a compact reproducibility package: raw synthetic data, formulas or code, version information, one chart, a results table and a short read-me file. Give every file and column a meaningful name and avoid values copied manually between tools. Re-run from a clean state and confirm that outputs are regenerated rather than cached. Ask a peer to alter one declared input and predict the direction of change before execution. Compare the prediction with the result and investigate any disagreement. Add a limitations section naming data coverage, numerical resolution, model assumptions and the next useful measurement. Archive corrections instead of erasing them so the reasoning trail remains visible. Conclude with what the calculation demonstrates, what it does not demonstrate and which qualified professional or authoritative standard would govern a real application.
