1.4. Appendix: Monte Carlo Pi PythonΒΆ
import random as r
import math as m
import matplotlib.pyplot as plt
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
# Random Seed
r.seed(42)
def estimatePI(n_trials=10):
successfulHits = 0
circleRadius = 0.5
squareLength = 1.0
inside_x,inside_y=[],[]
outside_x,outside_y=[],[]
# Iterate for the number of darts.
for i in range(0, n_trials):
x=0 # Your CODE HERE
pi = 0 # Estimate Pi
print(f"{pi:.10f}")
fig, ax=plt.subplots(1, figsize=(5,5))
ax.scatter(inside_x,inside_y)
ax.scatter(outside_x,outside_y)
plt.show()
The below code provides an interactive widget with a slider that will redraw the plot once you change the slider.
You can also simply run estimatePI(n_trials=100) to run the function once.
If you struggle to generate the plot using the slider because of resource limitation, reduce the maximum of trials in the slider to max=10000 and calculate one estimation of \(\pi\) with a higher number of trials using the standalone function estimatePI(n_trials=SomeLargeNumber)
interact(estimatePI, n_trials=widgets.IntSlider(min=2, max=1000000, step=100, value=1000))
<function __main__.estimatePI(n_trials=10)>