4.1.1.8 - Random numbers and controlled simulations (C#)

4.1.1.8 - Random numbers and controlled simulations (C#)

Random values let a program model chance without asking a user for every outcome. Learn the exact limits of C# random-number methods, then separate unpredictable sampling from deterministic checks of a simulation's logic.

C# route status: incomplete: runnable support pending. This lesson uses written C# and supplied traces with no Run control; runnable support is still required for complete onscreen Paper 1 preparation.

Random ranges and distributions

A random-number generator supplies values from a specified range; the programmer must map that range to the intended event.

Pseudorandom generator

An algorithm that produces a sequence intended to behave like random values, using an internal state that changes as values are requested.

With using System;, construct one generator and reuse it:

C#
Random generator = new Random();
int die = generator.Next(1, 7);
int slot = generator.Next(10);
double fraction = generator.NextDouble();

Next(minimum, maximum) includes the minimum and excludes the maximum. Thus die is one of 1–6. Next(10) produces one of 0–9. NextDouble() gives a double at least 0.0 and less than 1.0. Do not predict an exact sample unless the task supplies generator results. Next(1, 6) wrongly excludes six from a normal die.

The integer method is intended to sample its possible integers uniformly. In a small finite sample, counts usually differ; a fair die does not have to show each face once every six throws. To model a 30% success chance, generator.Next(1, 101) <= 30 selects 30 of the 100 possible integers. To choose from an array, generate an index from 0 to its length exclusive, and only do so when the array is nonempty.

A seeded generator, such as new Random(42), permits repeatable sequences in the same implementation when calls occur in the same order. Do not rely on a specific seeded sequence across every .NET version. Ordinary Random is for simulation and sampling, not security-sensitive keys or passwords.

Testing nondeterministic programs

Testing a random program requires separate checks of its range, its decision logic and its behaviour across many samples.

One test cannot insist that the next die roll is six: any valid face is possible. Check that every sampled face lies within 1–6 and that the program performs the required number of trials. Sampling can expose an out-of-range value, but absence of one in a finite sample alone does not prove that the range expression is correct; inspect the source too.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account