Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Background Information: People have spent lots of time playing around with the LCG algorithm and theyve found values of a, b, and c that make

Background Information:

People have spent lots of time playing around with the LCG algorithm and theyve found values of a, b, and c that make this an extremely good pseudorandom number generator. For example, the authors of Numerical Recipes (a handbook of numerical methods for C++ and FORTRAN) suggest using an LCG with

a = 1664525 b = 1013904223 c = 232

For given values of a, b, c, and seed (y0) the LCG algorithm will generate exactly the same sequence of pseudorandom numbers in every simulation. We usually dont want this and so the key is to find a way to have the program start with a different seed value in each simulation. One common strategy for obtaining a seed is to have the LCG function read the computers clock whenever the function is called and convert the time into a seed value.

Pseudorandom number generators such as the LCG algorithm are great examples of how a deterministic model can be successfully used to describe a stochastic system. In Python, we will make good use of pseudorandom numbers functions available in the random and numpy.random modules in several of our exercises this semester. A very basic version of a Python function for generating pseudorandom numbers uniformly distributed between 0 and 1 is shown below.

image text in transcribed

Problem Statement:

a.)

Create your own function to generate uniformly-distributed pseudorandom numbers based on the example above. You may use this code as a starting point, but your function will be much more versatile. Your function must be designed as follows:

image text in transcribedYour function must be named p1 and a user should be able to call your function using positional arguments, keyword arguments, or a mixture of both. For example, calls that should work for your function include: p1()

p1(5)

p1((3,20), 'RANDU')

p1(200, returnSeed = True)

p1(method = 'RANDU', size = (4, 4))

The method used in the given program for generating a seed was not particularly good; try to devise a better strategy for generating a seed in your program. Although there are websites such as www.random.org and qrng.anu.edu.au that claim to provide true random numbers, you cannot use these in this assignment not even for just getting a seed. You must generate your seed internally (e.g., no reliance on an internet connection). Important: This function must ONLY return the output random number(s) and the seed (if requested) and nothing else! No graphs, no prompts, no print() statements! Your function should run silent except for the outputs returned to the caller.

b.)

Write a Python script that analyzes the results of your random number function to see if you can discover any evidence that it does not generate decent random numbers. One way of doing this is to use your function to generate a large number of points that can be graphed in a 3-dimensional plot; if the generator is a good one, this plot should have no obvious patterns the points should be randomly distributed throughout space. For example, a single call to your function such as p1((5000,3)) should return an ndarray with 5000 rows and 3 columns, which could then be plotted in a 3-dimensional scatter plot (the columns being the x-, y- and z-coordinates). Prepare such plots to compare results for the two LCG generators (NR and RANDU) and also NumPys own uniform random number generator, np.random.random_sample(). Hint: rotate the plots in 3D to see if any patterns are observed from different perspectives.

c.)

You should observe something odd with the RANDU generator in part (b); think about the consequences of using this generator to model stochastic processes. Hint: the problem with RANDU surfaces when the (x,y,z) coordinates for each point are obtained from 3 successive calls to the function.

d.)

To test the method you used to generate a seed value, you could do something similar to the approach in (b). You could, for example, populate the 5000 3 matrix with 15,000 seed values. Use this approach or some other approach that you think would be appropriate to test your algorithm for calculating seed values.

e.)

Imagine a square dartboard with an inscribed circle and a rather unskilled dart thrower who manages to hit the dartboard every time but at random locations. After many darts have been thrown, if their distribution is random and uniform then the value of pi can be estimated from calculating the proportion of darts that landed within the circle. (Be sure you can explain why this is true!)

Simulate this experiment using your random number generator from part a. Your function must be named p2. You function should allow a user to specify the total number of throws and the LCG method (NR, RANDU, ) used by the generator. A figure should be created illustrating the dartboard and location of the throws. The estimated value of pi should be an output variable of your function (and it would also be very nice to display it in the figure as well). Your function p2 must be designed as follows:

image text in transcribedNote that the problem with RANDU can also be observed in the dartboard simulation if the x and y coordinates of each point are generated by two consecutive calls to the random number generator.

Include the following:

- a brief description of your strategy for setting a seed value in part a

- discuss your results and observations from parts b-d, including graphs that help make your point

- explain how you estimated pi from the simulation results in part e

- screenshot of a simulation result from your program from part e

import numpy as np import time def prng_basic(n, method = 'NR'): Generate uniformly distributed random numbers between 0 and 1 Parameters --------- - n : number of random numbers to generate type: integer method : algorithm 'R' or 'RANDU' type: float Returns - - - - - - - Vector of uniformly-distributed random numbers between 0 and 1 type: ndarray Example >>> prng_basic(12, 'NR') if method == 'NR': a = 1664525 b = 1013904223 C = 2**32 elif method == 'RANDU': a = 65539 b = 0 C = 2**31 else: raise Exception('Error - no such method') # % is the modulo operator in Python # note that x % 1 gets the fractional part of a float x seed = ((time.time() % 1) * 1e6) % C y = np.zeros(n) y[@] = seed for i in range(1, n): y[i] = (a * y[i-1] + b) % c return y lo name parameters default data type value description Shape of output; if None, a size int or tuple of ints None single value is returned. LCG algorithm to be used; accepted values are 'NR' or method string 'NR' 'RANDU'. If you wish, you may also invent your own method and include it as well. Seed to be used in LCG float None algorithm; if None, your program will generate a seed. Specifies whether to return returnSeed Boolean False seed value as output. Returns a single float or an ndarray of floats. If returnSeed is True then the seed is also returned as a second element of the output tuple. seed out default value name data type description nThrows int 200 Number of darts to be thrown parameters method string 'NR' LCG algorithm to be used; accepted values are 'NR' or 'RANDU'. If you wish, you may also invent your own method and include it as well. out Returns estimate for a import numpy as np import time def prng_basic(n, method = 'NR'): Generate uniformly distributed random numbers between 0 and 1 Parameters --------- - n : number of random numbers to generate type: integer method : algorithm 'R' or 'RANDU' type: float Returns - - - - - - - Vector of uniformly-distributed random numbers between 0 and 1 type: ndarray Example >>> prng_basic(12, 'NR') if method == 'NR': a = 1664525 b = 1013904223 C = 2**32 elif method == 'RANDU': a = 65539 b = 0 C = 2**31 else: raise Exception('Error - no such method') # % is the modulo operator in Python # note that x % 1 gets the fractional part of a float x seed = ((time.time() % 1) * 1e6) % C y = np.zeros(n) y[@] = seed for i in range(1, n): y[i] = (a * y[i-1] + b) % c return y lo name parameters default data type value description Shape of output; if None, a size int or tuple of ints None single value is returned. LCG algorithm to be used; accepted values are 'NR' or method string 'NR' 'RANDU'. If you wish, you may also invent your own method and include it as well. Seed to be used in LCG float None algorithm; if None, your program will generate a seed. Specifies whether to return returnSeed Boolean False seed value as output. Returns a single float or an ndarray of floats. If returnSeed is True then the seed is also returned as a second element of the output tuple. seed out default value name data type description nThrows int 200 Number of darts to be thrown parameters method string 'NR' LCG algorithm to be used; accepted values are 'NR' or 'RANDU'. If you wish, you may also invent your own method and include it as well. out Returns estimate for a

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Processing Fundamentals, Design, and Implementation

Authors: David M. Kroenke, David J. Auer

14th edition

133876705, 9781292107639, 1292107634, 978-0133876703

More Books

Students also viewed these Databases questions