In: Math
This problem is also a Monte Carlo simulation, but this time in the continuous domain: must use the following fact: a circle inscribed in a unit square
has as radius of 0.5 and an area of ?∗(0.52)=?4.π∗(0.52)=π4.
Therefore, if you generate num_trials random points in the unit square, and count how many land inside the circle, you can calculate an approximation of ?
For this problem, you must create code in python
(B) Without drawing the diagram, calculate the value of ? you would get from 105 trials.
(C) After completing (B), try to get a more accurate value for ? by increasing the number of trials.The results will depend on your machine
import numpy as np
import matplotlib.pyplot as pl
trials = 105
counts = 0
for i in range(trials):
x =
np.random.random()
y =
np.random.random()
x2 =
x**2
y2 =
y**2
x_y = x2 +
y2
dxy =
np.sqrt(x_y)
if dxy <=
1:
counts = counts + 1
print ("number of trial =" ,trials ,"pi was approximated as ::",4*counts/trials)
you can chane the value of trials to larger number to see improvement in pi
Note that function name is approx_pi.py