Skip to topic
    ← Back to course topics

    Random number generation in a programming language — AQA A-Level Computer Science

    Random number generation in computer programming involves creating numeric sequences that lack predictable patterns, typically using deterministic mathematical algorithms known as Pseudo-Random Number Generators (PRNGs). Unlike True Random Number Generators (TRNGs) that sample physical entropy, PRNGs rely on an initial seed value, making them repeatable and ideal for simulations, testing, and procedural generation.

    Random number generation in a programming language explained

    This statement is incomplete in the published specification: it ends at the word "random" and does not name the object being generated, such as integers or floating-point values.

    Read the full explanation

    Because the supplied source row contains no further words, this note teaches only the general, widely used idea that a programming language provides a random number generator. A random number generator produces values that appear unpredictable within a stated range, and most languages supply a function or library for this purpose. Programmers typically call the function with bounds, for example to obtain an integer from 1 to 6 to simulate a die roll. Learners should be familiar with calling such a function, understanding that the result changes between calls, and recognising that a seed can make a sequence repeatable for testing.

    Your focus

    1. Be familiar with, and be able to use, random

    Which command word is this?

    Set out the technical causes or mechanics clearly. For RNG, this often requires linking the mathematical determinism of PRNGs to why seeds produce repeatable sequences.

    Random number generation in a programming language exam tips

    Topic Overview

    Random number generation (RNG) in programming underpins computational modelling, statistical simulations, game mechanics, and cryptographic security. Because standard computers operate deterministically using digital logic, generating genuine non-deterministic randomness in pure software is impossible without measuring external physical entropy.

    Consequently, software environments rely primarily on Pseudo-Random Number Generators (PRNGs), which apply mathematical formulas to generate sequences that satisfy statistical tests for randomness. Understanding how PRNGs function, how their seeds govern outputs, and when to opt for True Random Number Generators (TRNGs) is critical for both Paper 1 algorithmic challenges and Paper 2 theoretical assessments.

    Key Concepts
    • →Pseudo-Random Number Generators (PRNGs): Deterministic algorithms that generate sequences mimicking randomness; given the same internal state or seed, they always reproduce identical numbers.
    • →Seed Value: The initial numerical state supplied to a PRNG algorithm; commonly derived from system hardware clocks (Unix epoch time in milliseconds) to vary runs automatically.
    • →True Random Number Generators (TRNGs): Systems that harvest non-deterministic physical entropy from external hardware phenomena, such as thermal noise, radioactive decay, or keystroke timing.
    • →Periodicity: The maximum sequence length after which a PRNG exhausts all internal states and begins repeating its generated values exactly.
    • →Uniform Distribution: The property whereby every discrete outcome within a target range has an identical mathematical probability of being selected.
    Marking Points
    • Identifies that a language provides a function or library that returns random values.
    • Explains that the bounds passed to the function determine the range of possible results.
    • Recognises that repeated calls normally produce different values.
    • Describes using a seed to make a generated sequence repeatable.
    Examiner Tips
    • 💡Use a concrete example such as a die roll to show the range of values produced.
    • 💡Name the bounds you use and state whether they are inclusive.
    • 💡If the question asks about repeatability, mention the seed explicitly.
    • 💡Use exact terminology: Always contrast 'deterministic algorithmic PRNGs' with 'entropy-based non-deterministic TRNGs' to secure full marks in comparative essay questions.
    • 💡Check boundary indices: In Paper 1 coding questions, verify your lower and upper bounds when converting floating-point random numbers to integer ranges to avoid off-by-one errors.
    • 💡Highlight reproducibility in testing: When discussing simulation algorithms (e.g. Monte Carlo), emphasize that fixed seed values allow developers to recreate and debug specific program states.
    Common Mistakes
    • Assumes a generated value is truly unpredictable in every case; most programming random generators are pseudo-random, so state this where relevant.
    • Uses a range that excludes the intended maximum, such as a die roll giving 0 to 5; check whether the upper bound is inclusive.
    • Expects the same value on every call without setting a seed; the value normally changes between calls.
    • Assuming built-in random functions produce true chaos: Standard software libraries execute deterministic mathematics; without dedicated physical entropy sources, no software algorithm is truly non-deterministic.
    • Re-seeding inside a rapid loop: Developers often call seed(time()) inside a fast iteration, causing the exact same timestamp to be read repeatedly, which generates identical numbers instead of random ones.
    • Assuming uniform distribution guarantees cryptographic safety: A PRNG can distribute numbers evenly across a range yet still be vulnerable if an attacker can deduce internal states from past outputs.
    Revision Plan
    1. 1Day 1-2: Review core definitions, distinguishing between PRNGs and TRNGs and understanding sources of physical entropy.
    2. 2Day 3-4: Practise manual mathematical tracing of Linear Congruential Generators (LCGs) using modulo arithmetic.
    3. 3Day 5-6: Write and test code scripts in Python or C# that simulate card shuffling (Fisher-Yates) and investigate how seed values fix output sequences.
    4. 4Day 7: Work through past AQA exam questions focusing on simulation modelling, seed utility, and cryptographic key generation.
    Exam Question Types
    • 📋Algorithmic trace questions: Calculating sequential outputs of recurrence relations like LCGs with specified multiplier, increment, and modulus values.
    • 📋Pseudocode and implementation tasks: Writing code to simulate stochastic processes, such as dice rolling, lottery draws without replacement, or shuffling.
    • 📋Evaluation and comparative questions: Explaining the technical differences, advantages, and limitations of PRNGs versus TRNGs in cybersecurity versus game programming.
    Command Word Expectations (AQA)
    Explain

    Set out the technical causes or mechanics clearly. For RNG, this often requires linking the mathematical determinism of PRNGs to why seeds produce repeatable sequences.

    Compare

    Identify explicit similarities and differences between two concepts (e.g. PRNGs vs TRNGs) across clear metrics such as speed, periodicity, reproducibility, and cryptographic security.

    State

    Give a specific, concise factual answer without elaboration, such as naming a physical entropy source used by a TRNG.

    How Students Lose Marks (Examiner Pitfalls)
    Pitfall: Confusing pseudo-random numbers with truly random numbers and asserting that software built-in functions like Python's random() produce natural chaos.
    ❌ Weak Answer (Loses Marks):Computers generate completely random numbers when you call the random function because the CPU picks a number entirely by chance.
    Example improved answer:Standard software random functions are pseudo-random; they use deterministic mathematical algorithms (such as the Mersenne Twister or Linear Congruential Generators) starting from an initial seed. Given identical seeds and algorithms, the resulting sequence is fully reproducible and eventually periodic.
    Examiner Tip: Always mention 'seed' and 'deterministic algorithm' when explaining why PRNGs are not truly random.
    Pitfall: Failing to distinguish between the requirement of reproducibility in testing versus unpredictability in security.
    ❌ Weak Answer (Loses Marks):You always use a seed so that you can repeat the game if the player dies.
    Example improved answer:Deterministic seeding is essential in software testing and scientific simulations to reproduce bugs and verify results, but catastrophic in cryptography. Cryptographic applications require non-deterministic True Random Number Generators (TRNGs) or cryptographically secure PRNGs to prevent adversaries from calculating secret keys.
    Examiner Tip: Contrast statistical randomness (sufficient for games and simulations) with cryptographic unpredictability when answering security-focused questions.
    Step-by-Step Worked Solutions

    Question: A Linear Congruential Generator (LCG) is defined by the relation X_{n+1} = (a * X_n + c) MOD m. Given parameters a = 5, c = 3, modulus m = 16, and an initial seed X_0 = 7, calculate the next two pseudo-random integers X_1 and X_2 in the sequence.

    1. 1.Step 1: Identify the recurrence relation formula: X_{n+1} = (a * X_n + c) MOD m, with parameters a = 5, c = 3, m = 16, and initial seed X_0 = 7.
    2. 2.Step 2: Calculate X_1 using X_0: (5 * 7 + 3) = 35 + 3 = 38. Then compute 38 MOD 16. Since 16 * 2 = 32, the remainder is 38 - 32 = 6. Therefore, X_1 = 6.
    3. 3.Step 3: Calculate X_2 using X_1 as the new state: (5 * 6 + 3) = 30 + 3 = 33. Then compute 33 MOD 16. Since 16 * 2 = 32, the remainder is 33 - 32 = 1. Therefore, X_2 = 1.
    Final Answer: X_1 = 6, X_2 = 1

    Question: A programmer uses a pseudo-random function random() that generates a real number r uniformly distributed such that 0.0 <= r < 1.0. Write an expression using integer truncation (INT) or floor arithmetic to simulate the roll of a fair six-sided die (numbers 1 to 6 inclusive), and explain the mathematical mapping.

    1. 1.Step 1: Define the continuous range produced by the base generator: 0.0 <= random() < 1.0.
    2. 2.Step 2: Scale the range by multiplying by the total count of discrete outcomes (6): 0.0 <= random() * 6 < 6.0.
    3. 3.Step 3: Truncate or floor the result to discrete integer buckets: INT(random() * 6) yields integers {0, 1, 2, 3, 4, 5} with equal probability (each bucket having width 1.0).
    4. 4.Step 4: Shift the discrete range by adding 1 to map to a standard die: INT(random() * 6) + 1 yields integers {1, 2, 3, 4, 5, 6}.
    Final Answer: Expression: INT(random() * 6) + 1
    Active Recall Memory Test
    What is the primary operational difference between a PRNG and a TRNG?
    Key Fact: A PRNG is a deterministic mathematical algorithm starting from a seed, whereas a TRNG derives randomness from non-deterministic physical entropy.
    Why is setting a static, fixed seed beneficial during software development?
    Key Fact: A fixed seed produces the exact same sequence of pseudo-random numbers on every run, enabling developers to reproduce and debug specific test scenarios.
    What mathematical operation is universally used in PRNGs like Linear Congruential Generators to keep values within a bounded range?
    Key Fact: Modulo arithmetic (MOD).
    Why are standard PRNGs unsuitable for generating cryptographic keys?
    Key Fact: Standard PRNGs are deterministic; an attacker who discovers the algorithm and internal state can predict all previous and future outputs.
    Frequently Asked Questions
    Why can't computers generate genuinely random numbers using software alone?
    Standard digital computers are built on deterministic logic circuits that execute defined binary operations. Given the same inputs and machine instructions, a computer must yield the exact same output. Pure software cannot produce authentic randomness without sampling an external, non-deterministic analog phenomenon, such as thermal noise or electrical fluctuations.
    What actually happens when I pass a seed into a random function?
    The seed initialises the internal state vector or starting numerical variable of the PRNG algorithm. Every subsequent call to generate a random number applies a fixed mathematical function to transform that internal state into a new value. If you initialise the generator with the identical seed on separate runs, the exact same series of numbers will be produced every time.
    Why is system time commonly used as a default random seed?
    System time (measured as milliseconds or nanoseconds since the Unix epoch) changes continuously with each passing moment. Using it as a seed ensures that each time an application is launched under normal circumstances, it begins from a different starting state. However, because system time is predictable, it must never be used to seed security-sensitive algorithms.
    What is the difference between a standard PRNG and a CSPRNG?
    A Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) satisfies rigorous security requirements that standard PRNGs do not. Specifically, CSPRNGs pass the 'next-bit test', meaning that given the first k bits of a sequence, an attacker with polynomial computational power cannot predict the (k+1)th bit with a probability significantly greater than 50%.
    What is the period of a pseudo-random number generator?
    The period is the number of values generated before the algorithm cycles back to its original internal state and repeats the sequence. Because PRNGs have finite internal memory states, all PRNGs will eventually repeat. Modern algorithms like the Mersenne Twister have vast periods (2^19937 - 1), ensuring repetitions never occur in standard real-world applications.