We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 8a5b038 commit d88f22bCopy full SHA for d88f22b
Exercises/ex18_MonteCarlo.py
@@ -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