Skip to content

Commit 725b033

Browse files
authored
Add files via upload
Predicting the value of Pi for differnet number of randomly generated samples. The samples are uniformly generated.
1 parent a6b49cb commit 725b033

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

predicting_pi/predicting_pi.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import mpmath
2+
import matplotlib.pyplot as plt
3+
4+
def estimate_pi(num_samples):
5+
points_inside_circle = 0
6+
7+
for _ in range(num_samples):
8+
x = mpmath.rand()
9+
y = mpmath.rand()
10+
11+
distance = x**2 + y**2
12+
13+
if distance <= 1:
14+
points_inside_circle += 1
15+
16+
pi_estimate = mpmath.mpf(4 * points_inside_circle) / mpmath.mpf(num_samples)
17+
return pi_estimate
18+
19+
# Set the precision to 30 decimal places
20+
mpmath.mp.dps = 30
21+
22+
# List to store the estimated values of pi for different sample sizes
23+
pi_estimates = []
24+
25+
# List of different sample sizes
26+
sample_sizes = [10, 100, 1000, 10000, 100000, 1000000]
27+
28+
# Estimating pi for each sample size
29+
for num_samples in sample_sizes:
30+
pi_approximation = estimate_pi(num_samples)
31+
pi_estimates.append(pi_approximation)
32+
33+
# Plotting the results
34+
plt.plot(sample_sizes, pi_estimates, marker='o')
35+
plt.xscale('log') # Use a logarithmic scale for the x-axis
36+
plt.axhline(y=mpmath.pi, color='r', linestyle='--', label='True value of pi')
37+
plt.xlabel('Number of Samples')
38+
plt.ylabel('Approximation of pi')
39+
plt.title('Monte Carlo Estimation of Pi for Varying # of Samples')
40+
plt.legend()
41+
plt.show()

0 commit comments

Comments
 (0)