by sillysaurus3 · 11y ago · 0 comments
def fib(n):
import math
r5 = math.sqrt(5)
x = pow((1 + r5) / 2, n)
x -= pow((1 - r5) / 2, n)
return x / r5
$ python fib.py 4
3.0
$ python fib.py 5
5.0
$ python fib.py 50
12586269025.0
$ python fib.py 5000
OverflowError: (34, 'Result too large')
So we add arbitrary precision. Uglier, but supports any n: def fib(n):
from math import sqrt
from decimal import Decimal
r5 = Decimal(sqrt(5))
x = pow((1 + r5) / 2, n)
x -= pow((1 - r5) / 2, n)
return x / r5
$ python fib.py 4
3.000000000000000242931577139
$ python fib.py 5
5.000000000000000607328942851
$ python fib.py 50000
1.077773489309106593392984005E+10449
$ python fib.py 50309230
8.147201098193506535089177522E+10514006
Or does it? $ python fib.py 50309230390
decimal.Overflow: above Emax
This was fun. Computing fib(50309230390) is left as an exercise for the reader.Wolfram alpha verifies this is correct for Fib 50,000: http://www.wolframalpha.com/input/?i=Fib+50000
Edit: Looks like sillysaurus3 edited his comment.
The formula came from section 17.3.2, which goes into detail about how to derive it.