Skip to content

Instantly share code, notes, and snippets.

@Lukas0025
Last active September 13, 2022 19:46
Show Gist options
  • Save Lukas0025/176fa21648f72ed19b64c3b49b30c804 to your computer and use it in GitHub Desktop.
Save Lukas0025/176fa21648f72ed19b64c3b49b30c804 to your computer and use it in GitHub Desktop.
Caclculate pi by random numbers
# Calculate pi by random numbers between 0 and 1
# @autor Lukáš Plevač <xpleva07@vutbr.cz> (BUT FIT)
# @date 1.6.2021
# CC0 license - No Rights Reserved.
import random
import math
##
# Calculate distance between point and [0,0]
# @param point - array with x and y of point
# @return float distance
def distance_from_0(point):
return math.sqrt(point[0] ** 2 + point[1] ** 2)
##
# Calculate pi using random between 0 and 1
# @param n_points - number of random points for calculation
# @return float number near to pi number
def calc_pi(n_points = 500):
# number of points in cirlce
points_in = 0
for _ in range(n_points):
point = [random.uniform(0,1), random.uniform(0,1)]
if distance_from_0(point) <= 1:
points_in += 1
return points_in / n_points * 4
## test it
print(calc_pi(9999999)) # 3.1416787141678713
# Maximal error is 1 / sqrt(n_points) => Error 0.0003162277818282274
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment