# Code for Monte Carlo class, Jonathan Goodman # http://www.math.nyu.edu/faculty/goodman/teaching/MonteCarlo20/ # SamplerDemo.py # The author gives permission for anyone to use this publicly posted # code for any purpose. The code was written for teaching, not research # or commercial use. It has not been tested thoroughly and probably has # serious bugs. Results may be inaccurate, incorrect, or just wrong. # illustrate using the Python random number generator from numpy version 19 from numpy.random import Generator, PCG64 # numpy randon number generator routines import sys # for the maxsize function print("\n Illustrate the random number generator from numpy version 19\n") bg1 = PCG64(12345) # instantiate a bit generator with seed 12345 bg2 = PCG64(12345) # another bit generator with the same seed rg = Generator(bg1) # instantiate a random number generator with ... # ... the first bit generator mr = sys.maxsize # supposedly the largest intetege, but not really print(" first three numbers from seed 12345\n") for i in range(3): r = bg2.random_raw() # integer directly from the bit generator ... x =.5*(r/mr) # ... made into a float between 0 and 1 y = rg.random() # uniform random numbers from the generator xyFormat = " x is {x:11.8f}, y is {y:11.8f}" output = xyFormat.format( x = x, y = y) print(output + ", r is " + str(r) + ", of type " + str(type(r))) s = rg.__getstate__() # the first random number generator "state" print("\n next three numbers in this sequence\n") for i in range(3): r = bg2.random_raw() # integer directly from the bit generator ... x =.5*(r/mr) # ... made into a float between 0 and 1 y = rg.random() # uniform random numbers from the generator xyFormat = " x is {x:11.8f}, y is {y:11.8f}" output = xyFormat.format( x = x, y = y) print(output + ", r is " + str(r) + ", of type " + str(type(r))) rg.__setstate__(s) # reset the state to where it was after the first two numbers ... # ... and generate again, should reproduce 3-rd and 4-th numbers print("\n after resetting the state\n") for i in range(3): r = bg2.random_raw() # integer directly from the bit generator ... x =.5*(r/mr) # ... made into a float between 0 and 1 y = rg.random() # uniform random numbers from the generator xyFormat = " x is {x:11.8f}, y is {y:11.8f}" output = xyFormat.format( x = x, y = y) print(output + ", r is " + str(r) + ", of type " + str(type(r))) print("\n Types of random number generator objets \n") print("bg has type: " + str(type(bg1))) print("rg has type: " + str(type(rg ))) print("s has type: " + str(type(s ))) print("the items in s are:") for name in s: print(" " + "\"" + name + "\": " + str(s[name]))