Skip to content

Instantly share code, notes, and snippets.

@Lukas0025
Last active June 2, 2021 20:52
Show Gist options
  • Save Lukas0025/b33c2425614aebdd9685a5567dd74458 to your computer and use it in GitHub Desktop.
Save Lukas0025/b33c2425614aebdd9685a5567dd74458 to your computer and use it in GitHub Desktop.
Calculate pi using numeric integration
# Calculate pi using numeric integration
# @autor Lukáš Plevač <xpleva07@vutbr.cz> (BUT FIT)
# @date 2.6.2021
# CC0 license - No Rights Reserved.
#
# taken from the relationship:
#
# pi * r ** 2 S of circle
# ------------ = --------------------------
# (2r) ** 2 S of square around circle
#
# let r = 1
#
# pi SC
# ------- = ----
# 4 SS
#
# pi = SC / SS * 4
#
from numpy import arange
##
# Is point in circle with r = 1 and s = [0,0]
# @param point - array with x and y of point
# @return bool
def in_circle(point):
return (point[0] ** 2 + point[1] ** 2) <= 1 # from distance of point and [0,0]
##
# Calculate pi using Numeric integral
# @param step - size of step for numeric integration
# @return float number near to pi number
def pi(step = 0.001):
c_points = 0 # mumber of points in circle
t_points = 0 # number of points in total (square)
# Numeric integral of 1/4 circle and square 0 .. 1
for y in arange(0,1,step):
for x in arange(0,1,step):
if in_circle([x,y]):
c_points += 1
t_points += 1
# integration of circle can by calc as c_points * (step ** 2) and of square is t_points * (step ** 2)
return c_points / t_points * 4 # (step ** 2) is in fraction in denominator and numerator
## test it
print(pi(0.0003)) # 3.1415396584750237
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment