0
def calculate_pi(number_of_drops):

in_circle = 0
in_square = 0

for i in range(number_of_drops):
    x = random.random()
    y = random.random()

    if math.sqrt(x*x+y*y) <= 1:
        in_circle += 1

    in_square += 1

return in_circle / in_square * 4

How can I plot this function wiht x being the input of the function and y the return output of the function using matplotlib ideally?

1 Answer 1

2

Here is a simple solution based on numpy (not math though) and matplotlib

import numpy as np
from matplotlib import pyplot as plt 


def calculate_pi(number_of_drops):
    
    samples = np.random.uniform(-1,1,size=(number_of_drops,2))
    criterion = np.sum(samples**2,axis=1) 
    in_circle = np.where(criterion < 1)[0]
    in_square = np.where(criterion >= 1)[0]
    
    return len(in_circle)/len(in_square)

calculated_pis = [calculate_pi(num) for num in range(100,100000,500)]

plt.plot(calculated_pis)
plt.hlines(np.pi,0,len(calculated_pis))

running this script, you will obtain a similar figure

example

Sign up to request clarification or add additional context in comments.

2 Comments

That is very good! Thanks for that. However, I was rather looking for a plot that shows how close the return of the function gets to the real number of pi with increased number of throws.
@F.V. You're welcome, check out my updated post.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.