Welcome, guest | Sign In | My Account | Store | Cart

Calculating e using Continued Fraction

Python, 15 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Calculating e using Continued Fraction
# http://en.wikipedia.org/wiki/Continued_fraction
import math
n = 18 # number of iterations
x = 0.0
for i in range(n, 0, -1):

    if i % 3 == 1:
        j = int(i / 3) * 2
    else:
        j = 1

    x = 1.0 / (x + j)

print x + 1, math.e

6 comments

FB36 (author) 10 years, 6 months ago  # | flag
# Calculating PI using Continued Fraction
# http://en.wikipedia.org/wiki/Continued_fraction
import math
n = 100000000 # number of iterations
x = 0.0
for i in range(n, 0, -1):
    x = 1.0 / (x + 1.0 / i)
print x * 2.0 + 2.0, math.pi
FB36 (author) 10 years, 6 months ago  # | flag
# Calculating square-root using Continued Fraction
# http://en.wikipedia.org/wiki/Continued_fraction
import math
n = 21 # number of iterations
a = 2.0 # calculate sqrt(2)
x = 0.0
for i in range(n):
    x = 1.0 + (a - 1) / (1.0 + x)
print x, math.sqrt(a)
FB36 (author) 10 years, 6 months ago  # | flag
# Calculating nth-root using Newton Iteration
# http://en.wikipedia.org/wiki/Newton_iteration
import math
n = 2.0; a = 3.0 # calculate sqrt(3) 
eps = 1e-9 # max error allowed
x = a
while True:
    xnew = x - (x ** n - a) / (n * x ** (n - 1.0))
    if abs(x - xnew) <= eps: break
    x = xnew
print x, a ** (1.0 / n)
FB36 (author) 10 years, 6 months ago  # | flag
# Calculating PI using Mandelbrot Fractal (Point)
# http://en.wikipedia.org/wiki/Approximations_of_%CF%80
import math
k = 7 # number of decimal digits wanted
eps = 1.0 / 10 ** k
z = complex(-0.75, eps) ; c = z
n = 0
while True:
    n += 1
    z = z * z + c
    if abs(z) >= 2.0: break
print n * eps, math.pi
Dr. Stefan Gruenwald 9 years, 8 months ago  # | flag

Great! Here is another way of doing this. Also works for e, pi, sqrt(n) [n can be any integer not just 2 or 3]. Let me know if you want the code or explanation

#this calculates the digits of e
k, a, b, a1, b1 = 2, 3, 1, 8, 3 # 2 (always), 1st numerator, 1st denominator, 2nd numerator, 2nd denominator
result=[]
for i in xrange(20):
    p, q, k = k, k+1, k+1 # counter on top, counter on left side, always k+1
    a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
    d, d1 = a/b, a1/b1
    while d == d1:
        result.append(d)
        a, a1 = 10*(a%b), 10*(a1%b1)
        d, d1 = a/b, a1/b1  
result="".join(map(str,result))
print int(result)/10.0**(int(len(result))-1)
FB36 (author) 9 years, 8 months ago  # | flag

It looks like it is calculating digits of e one by one. Definitely more impressive than my examples :-)

You could just print the result this way though:

print result[0] + "." + result[1:]

Created by FB36 on Mon, 2 Sep 2013 (MIT)
Python recipes (4591)
FB36's recipes (148)

Required Modules

  • (none specified)

Other Information and Tasks