Last active
September 13, 2022 19:46
-
-
Save Lukas0025/176fa21648f72ed19b64c3b49b30c804 to your computer and use it in GitHub Desktop.
Caclculate pi by random numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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