I am using ran2()
function in c programming codes. ran2()
is known as more truly random number generator. I found that ran2()
is also generates numbers in same sequence. Why is it so?
ran2
takes a long type pointer variable.
The code of ran2()
is available in Numerical recipes.
Here I'm writing how I called the function:
float temp;
long *seed,seed1;
seed=&seed1;
temp=ran2(seed);
After calling this function multiple times and running multiple times I see that numbers of same sequence are generated every time. Correct me where I am doing the mistake and what modifications needed to get the truly random sequence every time.
The source code for ran2
in Numerical Recipes says “Call with idum
a negative integer to initialize”. The parameter of ran2
is long *idum
. So, to use ran2
, define a long
, set it to a negative value, and pass a pointer to it to ran2
. In non-sensitive uses, it is not uncommon to use the standard C time
function to get a value to use to initialize random number generation. You will need to ensure it is negative. So you can use:
long seed = time(0);
if (0 <= seed)
seed = -1 - seed;
…
float x;
…
x = ran2(&seed);