Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
| Download

📚 The CoCalc Library - books, templates and other resources

Views: 96168
License: OTHER
1
"""This module contains a code example related to
2
3
Think Python, 2nd Edition
4
by Allen Downey
5
http://thinkpython2.com
6
7
Copyright 2015 Allen Downey
8
9
License: http://creativecommons.org/licenses/by/4.0/
10
"""
11
12
from __future__ import print_function, division
13
14
import math
15
16
17
def factorial(n):
18
"""Computes factorial of n recursively."""
19
if n == 0:
20
return 1
21
else:
22
recurse = factorial(n-1)
23
result = n * recurse
24
return result
25
26
27
def estimate_pi():
28
"""Computes an estimate of pi.
29
30
Algorithm due to Srinivasa Ramanujan, from
31
http://en.wikipedia.org/wiki/Pi
32
"""
33
total = 0
34
k = 0
35
factor = 2 * math.sqrt(2) / 9801
36
while True:
37
num = factorial(4*k) * (1103 + 26390*k)
38
den = factorial(k)**4 * 396**(4*k)
39
term = factor * num / den
40
total += term
41
42
if abs(term) < 1e-15:
43
break
44
k += 1
45
46
return 1 / total
47
48
print(estimate_pi())
49
50