In: Computer Science
Write a python code that calculates π using numpy rand function.
We can use the famous monte carlo stimulation ot estimate the value of pi using random numbers. Let us understand it by an example.
Suppose we have a dart board of the following shape. Both the circle and the square are centred at the origin, and the circle has a radius r.
Area of circle =
Area of square =
Suppose when you start throwing darts to the board, then the dart might fall anywhere on the boars with an equal probability.
The probability, P, that the dart falls in the circle
is .
so
So we now generate random numbers x,y satisfying
if
then the point lies in the circle else it lies outside.
Here is the code along with the output to do so.
The code is well-commented and easy to understand if the answer helped you please upvote and if you have any doubts please comment i will surely help. please take care of the indentation while copying the code. Check from the screenshots provided.
Code:
# stimulate the value of pi using a monte carlo
stimulation
import numpy as np
import matplotlib.pyplot as plt
# scattering n points over the unit square
number_of_points = 1000000
points = np.random.rand(number_of_points,2)
# counting the points inside the unit circle
inside_circle_count = 0
for point in points:
if np.sqrt(point[0]**2 + point[1]**2) < 1:
inside_circle_count += 1
# The probablity is number of points inside the cirle divided by the total number of points
probablity = inside_circle_count/number_of_points
estimated_pi = probablity*4
exact_pi = np.pi
print("the estimated value of pi is:",estimated_pi)
print("the exact value of pi is:",exact_pi)