Skip to content

Instantly share code, notes, and snippets.

@scentoni
Last active May 30, 2020 02:04
Show Gist options
  • Save scentoni/b0c48d51b0b223518bd9f10f6ffd468e to your computer and use it in GitHub Desktop.
Save scentoni/b0c48d51b0b223518bd9f10f6ffd468e to your computer and use it in GitHub Desktop.
Exploring the Python decimal module and approximations of transcendental numbers
#!/usr/bin/python2.7
# How many digits can I remember? How good is that approximation?
import math
import decimal
def compute_pi():
"""Compute Pi to the current precision.
>>> print(pi())
3.141592653589793238462643383
"""
decimal.getcontext().prec += 2 # extra digits for intermediate steps
three = decimal.Decimal(3) # substitute "three=3.0" for regular floats
lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
while s != lasts:
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
decimal.getcontext().prec -= 2
return +s # unary plus applies the new precision
D = decimal.Decimal
decimal.getcontext().prec = 30
pi = compute_pi()
mypi = "3.14159265358979"
e = D(1).exp()
mye = "2.718281828459045"
def correct_digits(approximation, truth):
return -abs((approximation/truth).ln()).log10()
def print_correct_digits(approximation, truth):
digits = correct_digits(approximation, truth)
print(str(digits.quantize(D("1.00"))) + " correct digits of " + str(approximation) + ":" + str(truth))
approxlist = [
(D("3.14"), pi),
(D(22)/D(7), pi),
(D(355)/D(113), pi),
(D(mypi), pi),
(D(math.pi), pi),
(D("2.71"), e),
(D("2.72"), e),
(D(2721)/D(1001), e),
(D(mye), e),
(D(math.e), e),
(D(7)/D(12), D("1.5").ln()/D(2).ln()),
(D(31)/D(53), D("1.5").ln()/D(2).ln()),
]
for (a, t) in approxlist:
print_correct_digits(a, t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment