b) Estimating π
Imagine a Cartesian coordinate plane and a square of side length 2 centered at the origin.
The square will have vertices at (-1, -1), (-1, 1), (1, 1), and (1, -1). Inside the square, a circle
of radius 1 unit centered at origin as shown below.
Figure 1: Monte-Carlo Simulation
Now, we randomly generate a large number of points (x, y) within the square. The x and y
coordinates of these points should be between -1 and 1. For each generated point, we check
if the point falls within the circle (x
2 + y
2 ≤ 1) and keep a count of no. of points falling
inside the circle and total no. of random points generated.
Now the P(random point lie in the circle) = Are of the circle
Area of the square =
π
4
. We empirically estimate
this probability by random sampling done above. Therefore, π = 4 ×
Are of the circle
Area of the square .
Update: Use Python to simulate the above process and compare the π value obtained
using the pseudo-random number generator from the previous subtask and random.random()
function from random module in python.
Note: You must import the pseudo rand num gen(seed, k) function from part (a) .py file,
instead of copy-pasting the function code.
Assistant
To simulate the process described above in Python, we'll run a Monte Carlo simulation to estimate π. We'll use both a custom pseudo-random number generator that was presumably created in a part (a) we don't have access to and the built-in function from Python's module for comparison.
User
q1_a
import time
import matplotlib.pyplot as plt
def pseudo_rand_num_gen(seed=None, k=1):
if seed is None:
seed = int(time.time()) # Use current system time as seed
code
Assistant
User
Cell In[21], line 31
print(f"Estimated π using pseudo RNG: {pi_estimate_pseudo_rng}“)
^
SyntaxError: unterminated string literal (detected at line 31)
Assistant
The error occurs because the closing quotation mark at the end of the print statement is not a standard ASCII double quote. The line contains a left double quotation mark (“) instead of the correct ASCII character (").
Let's correct the quotation marks. Here is the revised code snippet with the proper quotation marks:
python
print(f"Estimated π using pseudo RNG: {pi_estimate_pseudo_rng}")
print(f"Estimated π using built-in random.random(): {pi_estimate_random}")
Always ensure you are using the standard ASCII double quote (") or single quote (') for string literals in Python to avoid syntax errors.
User
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
The last line of your provided code snippet appears to have a missing parenthesis at the end of the print statement. Each function call or statement in Python that opens a parenthesis ( must also close it with a corresponding ).
The corrected lines should be:
python
User
not working
Assistant
I apologize for any confusion. Let's address the issue and get the code working for you.
random.random()
random
Below you'll find a Python script that performs the simulation using both methods. Please ensure you have a .py file containing the function pseudo_rand_num_gen(seed, k) from part (a) so you can import it.
python
# Assuming the part (a) code is saved in a file called 'part_a.py'
from part_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 x**2 + y**2 <= 1:
inside_circle += 1
return (inside_circle / total_points) * 4
# Set the seed and 'k' as needed for your pseudo random number generator
seed = 0 # Replace with your seed
k = 10000 # Replace with a suitable 'k' value
# Create a RNG function with our seed and k
def my_pseudo_random():
return pseudo_rand_num_gen(seed, k)
# Perform the Monte Carlo simulation with a large number of points
total_points = 1000000 # The more points, the better the estimation
pi_estimate_pseudo_rng = monte_carlo_pi_estimation(total_points, my_pseudo_random)
pi_estimate_random = monte_carlo_pi_estimation(total_points, random.random)
print(f"Estimated π using pseudo RNG: {pi_estimate_pseudo_rng}")
print(f"Estimated π using built-in random.random(): {pi_estimate_random}")
Replace seed and k with appropriate values based on how your pseudo_rand_num_gen function is implemented.
Please note: The accuracy of your pseudo-random number generator will greatly affect the precision of the π estimation. Python's random.random() is a well-tested and reliable random number generator that should give you a pretty accurate estimation, but the quality of a custom RNG can vary significantly.
The convergence of this method depends on the number of points used. Larger numbers of points tend to yield more accurate estimates, but they take more time to compute. The above script uses total_points = 1000000, which is usually sufficient to get an estimation accurate to a few decimal places.
seed_str = str(seed)
if len(seed_str) % 2 != 0:
seed_str = '0' + seed_str
n = len(seed_str)
rand_nums = []
for _ in range(k):
seed_squared = int(seed_str) ** 2
seed_squared_str = str(seed_squared).zfill(n * 2)
middle_digits = int(seed_squared_str[(n // 2): (n // 2 + n)])
rand_nums.append(middle_digits)
seed_str = str(middle_digits).zfill(n)
normalized_nums = [num / (10 ** n) for num in rand_nums]
plt.hist(normalized_nums, bins=max(10, k // 10), edgecolor='black')
plt.title('Pseudo-Random Numbers Distribution')
plt.xlabel('Number Range')
plt.ylabel('Frequency')
plt.show()
return normalized_nums
random_numbers = pseudo_rand_num_gen(k=100)
q1_B
Assuming the part (a) code is saved in a file called ‘part_a.py’
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:
inside_circle += 1
return (inside_circle / total_points) * 4
Set the seed and ‘k’ as needed for your pseudo random number generator
seed = 0 # Replace with your seed
k = 10000 # Replace with a suitable ‘k’ value
print(f"Estimated π using pseudo RNG: {pi_estimate_pseudo_rng}“)
print(f"Estimated π using built-in random.random(): {pi_estimate_random}”)
I can see that you've provided the implementation for the pseudo random number generator in q1_a and a modified version of the Monte Carlo simulation script in q1_B. There are a few issues that need to be addressed in your Monte Carlo simulation implementation:
The rand_func in the monte_carlo_pi_estimation function should return a single random number rather than an array of random numbers.
The function my_pseudo_random is calling pseudo_rand_num_gen with k set to 10000, but only a single random number is needed at a time.
Let's update the monte_carlo_pi_estimation function to use a generator that yields one random number at a time, and make sure we consider the correct seed value:
python
# 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 x**2 + y**2 <= 1: # Squaring must use `**`, not by just typing '2'
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)
print(f"Estimated π using pseudo RNG: {pi_estimate_pseudo_rng}")
print(f"Estimated π using built-in random.random(): {pi_estimate_random}")
Make sure you replace q1_a with the actual name of the module where pseudo_rand_num_gen is located if it's different.
Please note, we use a seed (ex: seed = 123), but you should use an integer that suits your case or that you may have been given in the problem statement.
This script should produce two estimates of π, one using the custom pseudo RNG and the other using Python's built-in random.random() function.
print(f"Estimated π using pseudo RNG: {pi_estimate_pseudo_rng}")
print(f"Estimated π using built-in random.random(): {pi_estimate_random}"
something is wrong
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:
python
# 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 x**2 + y**2 <= 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}")
Make sure you run this corrected version, and the SyntaxError should no longer occur, allowing your script to print the estimated values of π.
There's a mistake in the my_pseudo_random function. Since the pseudo_rand_num_gen generates a list of random numbers and we are calling it with k=1, we expect to get a list with a single number, not a number itself. The generator should get the first and only item from this list.
Here's how you would update the my_pseudo_random function:
python
def my_pseudo_random(seed):
while True:
num_list = pseudo_rand_num_gen(seed, k=1)
yield num_list[0] # Yield the first number from the list
When you make these changes, make sure that you do not recreate the random_generator inside the loop where you estimate the value of π; otherwise, you will get the same random number every time. Instead, create the generator once outside the monte_carlo_pi_estimation function.
Let's look at the updated and full working code:
python
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
y = rand_func() * 2 - 1
if x**2 + y**2 <= 1:
inside_circle += 1
return (inside_circle / total_points) * 4
def my_pseudo_random(seed):
while True:
num_list = pseudo_rand_num_gen(seed, k=1)
yield num_list[0] # Use the first (and only) number from the list
# Initialize the random number generator
seed = 123 # Set the seed
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}")
Run this code, and it should print out the estimated values of π using both the pseudo RNG and Python's built-in random.random function. If you still encounter any errors or issues, please let me know the specific error message or problem, and I will provide further assistance.