4.1.1.8 - Random numbers and controlled simulations (VB.NET)

4.1.1.8 - Random numbers and controlled simulations (VB.NET)

Learn to generate values in the intended range, trace random-dependent logic with supplied draws and test simulations without expecting one fixed result. This VB.NET route is written only and incomplete: runnable support pending.

Random ranges and outcome selection

Random number generation provides varying values for games, sampling and simulations. A pseudorandom generator uses an algorithm and internal state to produce a sequence that behaves like random choices for ordinary modelling; it is not a guarantee of cryptographic security.

Create a Random object, then reuse it for successive draws. Next(minimum, maximum) includes the minimum and excludes the maximum. Therefore a six-sided die requires an upper argument of 7.

VB.NET
Dim generator As New Random()
Dim die As Integer = generator.Next(1, 7)
Dim index As Integer = generator.Next(0, 5)
Dim fraction As Double = generator.NextDouble()
Dim distance As Double = 10 + 5 * fraction

The die can be 1–6; the index can be 0–4; NextDouble() is at least 0 and less than 1. The final expression scales that real range to at least 10 and less than 15. A single call to Next(1, 6) excludes 6, so its apparently reasonable bounds are wrong for a die. Rounding a scaled real number is a poor way to choose equally likely integer outcomes: endpoint intervals can differ in width. Use the integer generator for integer choices.

Under the ordinary uniform-choice model, each of the six permitted die faces is equally likely on each draw. This does not mean every block of six draws contains one of each. A short sequence can have repeated outcomes or omit a face without proving a defect. Choose the distribution that represents the situation: a fair die is uniform, while an event with probability 0.3 can use NextDouble() < 0.3.

Testing random-dependent programs

A test of random-dependent logic needs to separate the values generated from the way the program processes them. A changing output is not automatically an error, and an expected random range is not a prediction of one exact future value.

Continue this lesson.

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

Create free account