Confusion about `Random`

Paul Backus snarwin at gmail.com
Thu Dec 22 17:33:48 UTC 2022


On Thursday, 22 December 2022 at 16:23:16 UTC, jwatson-CO-edu 
wrote:
> I am confused about why Program 1 produces random output but 
> Program 2 does not.

The code you have posted as "Program 2" is incomplete, and cannot 
be compiled as-is. I have made some changes in order to get it to 
compile and produce useful output, resulting in the following 
program:

#### sparrow_core.d

```d
module sparrow_core;

import std.random;

Mt19937 rnd; // Randomness

void init_random(){
     // Seed the RNG with the clock
     rnd = Random( unpredictableSeed );
}

double rand01(){
     // Uniform random sampling in [0,1)
     return uniform( 0.0, 1.0, rnd);
}

void init_SPARROW(){
     // Populate necessary global structures
     init_random(); // --- RNG
}
```

#### app.d

```d
module app;

import sparrow_core;
import std.stdio;

void main(){
     init_SPARROW();
     foreach (i; 0 .. 6)
         writeln(rand01());
}
```

When I compile and run the above program, I get the following 
output:

```
0.289729
0.39377
0.693163
0.232496
0.388511
0.840994
```

So, as far as I can tell, there is nothing wrong with your code, 
and the random number generator is working as intended.

Most likely you have made a mistake somewhere in the part of the 
code that you did not post, and that mistake is what's causing 
the lack of randomness you observed in the output.


More information about the Digitalmars-d-learn mailing list