Computational Thinking Foundations#

from math import *
import numpy as np
x_min = 0
x_max = 1
y_min = 0
y_max = 1
def f(x):
  return sqrt(1 - x ** 2)
def monte_carlo(f, n):
  area = (x_max - x_min)*(y_max - y_min)  # Area of the recangle
  s = 0                                   # Success counter
  for i in range(n):
    rx = np.random.uniform(x_min, x_max)
    ry = np.random.uniform(x_min, y_max)
    if ry <= f(rx):
      s += 1
  return s * area/n
monte_carlo(f,10000)
0.7837