Question: write code below with import random function do not use numpy #New Updated Code import numpy as np import matplotlib.pyplot as plt import math import

write code below with import random function do not use numpy #New Updated Code
import numpy as np
import matplotlib.pyplot as plt
import math
import time
# Calculate pi using Monte Carlo method
def cal_pi(num_points):
x = np.random.uniform(-1,1, num_points)
y = np.random.uniform(-1,1, num_points)
in_circle = x**2+ y**2<=1
pi_est =4* np.sum(in_circle)/ num_points
return pi_est
# Function to calculate percent error
def per_error(est_pi):
return math.fabs((est_pi - math.pi)/ math.pi)*100
# Number of points to test
points =[10,100,1000,10000,100000,1000000]
errors =[]
# Calculate percent error for each number of points
for num_points in points:
pi_est = cal_pi(num_points)
error = per_error(pi_est)
errors.append(error)
print(f"Points: {num_points}, Pi Estimate: {pi_est}, Percent Error: {error:.2f}%")
# Plotting the percent error
plt.figure(figsize=(10,6))
plt.plot(points, errors, marker='o',color='green', linestyle='dashed')
plt.xscale('log')
plt.xlabel('Points')
plt.ylabel('Percent Error')
plt.title('Monte Carlo Method Percent Error in Pi Calculation via Numpy')
plt.grid(True)
plt.show()
n_samples =100
start = time.time()
end = time.time()
elap_time_100= end - start
print(f"Elapsed time for {n_samples} samples: {elap_time_100} seconds")
n_samples =10000000
start = time.time()
end = time.time()
elap_time_10000000= end - start
print(f"Elapsed time for {n_samples} samples: {elap_time_10000000} seconds")
# Measure performance for 1,000 steps
n_steps =1000
start = time.time()
end = time.time()
elap_time_1000_steps = end - start
print(f"Elapsed time for {n_steps} steps: {elap_time_1000_steps} seconds")

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!