print(f"Estimated π using pseudo RNG: {piestimatepseudorng}“) print(f"Estimated π using…
- User
print(f"Estimated π using pseudo RNG: {pi_estimate_pseudo_rng}“) print(f"Estimated π using built-in random.random(): {pi_estimate_random}”)
The updated script should now look like this:
Assuming the part (a) code is imported as pseudo_rand_num_gen
from q1_a import pseudo_rand_num_gen import random
def monte_carlo_pi_estimation(total_points, rand_func): inside_circle = 0 for _ in range(total_points): x = rand_func() * 2 - 1 # Scaling to range [-1, 1] y = rand_func() * 2 - 1 # Scaling to range [-1, 1] if x2 + y2 <= 1: # Use ** for squaring inside_circle += 1 return (inside_circle / total_points) * 4
Function generator that uses the custom pseudo_rand_num_gen to yield one random number at a time
def my_pseudo_random(seed): while True: for number in pseudo_rand_num_gen(seed, k=1): yield number
Initialize the random number generator
seed = 123 # Set the seed, it can be any integer random_generator = my_pseudo_random(seed)
Perform the Monte Carlo simulation with a large number of points
total_points = 1000000 # The more points, the better the estimation
We pass a lambda function to call ‘next()’ on our generator, fetching new random numbers
pi_estimate_pseudo_rng = monte_carlo_pi_estimation(total_points, lambda: next(random_generator)) pi_estimate_random = monte_carlo_pi_estimation(total_points, random.random)
Corrected print statements
print(f"Estimated π using pseudo RNG: {pi_estimate_pseudo_rng}“) print(f"Estimated π using built-in random.random(): {pi_estimate_random}”)
something is wrong
- Assistant
It appears there are a few issues in the provided script. Here are some corrections:
-
There is a small typo in the conditional check within the
monte_carlo_pi_estimation()function. The should be changed to in order to correctly calculate whether the point is inside the unit circle.
-