Note that this Monte Carlo method converges extremely slowly (to get each new decimal place we have to increase the number of random points by a factor of 10):
import math
import random
N = 10000
def f(x):
return math.sqrt(1.-x**2)
pi = 0.
for i in range(N):
xi, yi = random.random(), random.random()
if yi <= f(xi):
pi += 1.
pi *= 4 / N
print('pi is approximately {:.4f}'.format(pi))
The output is:
pi is approximately 3.1432