Skip to content

Instantly share code, notes, and snippets.

@adzarei
Created February 8, 2022 13:58
Show Gist options
  • Save adzarei/99eba8c76bab93a00e7fb2213a4c9167 to your computer and use it in GitHub Desktop.
Save adzarei/99eba8c76bab93a00e7fb2213a4c9167 to your computer and use it in GitHub Desktop.
Pi aproximation using the montecarlo approach written in python using numpy
import numpy as np
class PiMontecarloEstimates:
@staticmethod
def area_method(iter):
"""Calculates an aproximation of the value of PI by the area method using `iter` random points.
Area Method:
Given that Y = sqrt(1 - x**2) in the range [0, 1] draws a quarter of a circle of radius 1,
its area is PI/4.
An estimate can be calculated by drawing N random points in the space [0,1][0,1] and counting how many lie
under the curve drawn by Y. With this number and the total number of points, we can obtain a
ratio of points under the curve against total points, which is equivalent to the empiric probability of a
random point falling under the curve. If we multiply this ratio with the area of the space (1 x 1), we have
an aproximation of the area under the curve (PI/4). Finally, we multiply this value by 4 to get PI.
Expects `iter` to be a positive integer.
"""
# Uniformly distributed random values in range [0, 1].
# They represent X and Y dimensions of the random points.
x = np.random.rand(iter)
y = np.random.rand(iter)
# Function for 1/4 of a circle.
f_y = np.sqrt(1 - x**2)
# Ratio of random points that lie in the area of `f_y`.
# We only check the Y values b/c the share X values.
ratio_is_below = np.mean(y < f_y)
# Multiply by 4 to get PI.
return 4 * ratio_is_below
@staticmethod
def average_value_method(iter):
"""Calculates an aproximation of the value of PI by the average value method using `iter` random points.
Average Value Method:
Given that Y = sqrt(1 - x**2) in the range [0, 1] draws a quarter of a circle of radius 1,
its area is PI/4.
In this approach we generate N random samples of function Y to estimate the average value of the
continuous function on the interval [0, 1]. This average value approximates PI/4, so we finish by multiplying by 4.
Expects `iter` to be a positive integer.
"""
# Uniformly distributed random values in range [0, 1].
x = np.random.rand(iter)
y = np.sqrt(1 - x**2)
quarter_pi_estimate = np.mean(y)
return 4 * quarter_pi_estimate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment