An introduction to computational physics book15

Page 56

2.5 Random-number generators

// Method to generate a uniform random number in [0,1] // following x(i+1)=a*x(i) mod c with a=pow(7,5) and // c=pow(2,31)-1. Here the seed is a global variable. public static double ranf() { final int a = 16807, c = 2147483647, q = 127773, r = 2836; final double cd = c; int h = seed/q; int l = seed%q; int t = a*l-r*h; if (t > 0) seed = t; else seed = c+t; return seed/cd; }

Note that in the above code, we have used two more magic numbers q = c/a and r = c mod a. A program in Pascal that implements a method similar to that above is given by Park and Miller (1988). We can easily show that the above method modulates numbers with c = 231 − 1 on any computer with integers of 32 bits or more. To use this method, the seed needs to be a global variable that is returned each time that the method is called. To show that the method given here does implement the algorithm correctly, we can set the initial seed to be 1, and then after 10 000 steps, we should have 1 043 618 065 returned as the value of the seed (Park and Miller, 1988). The above generator has a period of 231 − 1. If a longer period is desired, we can create similar generators with higher-bit integers. For example, we can create a generator with a period of 263 − 1 for 64-bit integers with the following method. // Method to generate a uniform random number in [0,1] // following x(i+1)=a*x(i) mod c with a=pow(7,5) and // c=pow(2,63)-1. Here the seed is a global variable. public static double ranl() { final long a = 16807L, c = 9223372036854775807L, q = 548781581296767L, r = 12838L; final double cd = c; long h = seed/q; long l = seed%q; long t = a*l-r*h; if (t > 0) seed = t; else seed = c+t; return seed/cd; }

Note that we have used a = 75 , c = 263 − 1, q = c/a, and r = c mod a in the above method with the seed being a 64-bit (long) integer. In order to start the random-number generator differently every time, we need to have a systematic way of obtaining a different initial seed. Otherwise, we would not be able to obtain fair statistics. Almost every computer language has intrinsic

39


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.