Skip to content

Commit d88f22b

Browse files
committed
update
Signed-off-by: Harmouch101 <mahmoudddharmouchhh@gmail.com>
1 parent 8a5b038 commit d88f22b

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

Exercises/ex18_MonteCarlo.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Pi extimation
2+
# Great explanation: https://brilliant.org/wiki/monte-carlo/
3+
4+
import random, math
5+
6+
def pi_montecarlo(a, b, n):
7+
return 4 * (b -a ) * sum(math.sqrt(1 - random.uniform(a, b)**2)
8+
for i in range(n)) / n
9+
if __name__ == "__main__":
10+
n = int(input("Enter the number of iteration: "))
11+
print('|' + '-'*98 + '|')
12+
print(f"|{'n':<24}|{'approximation':^24}|{'absolute error':^24}|{'relative error':^23}|")
13+
print('|' + '-'*98+ '|')
14+
for i in range(1,n):
15+
n = 10 ** i
16+
approx = pi_montecarlo( 0, 1, n)
17+
error = math.pi - approx
18+
print(f'|{n:<24}|{approx:^24}|{error:^24}|{abs(error)/math.pi:^23}|')

0 commit comments

Comments
 (0)