Possible Duplicate:
Handling very large numbers in Python
I have a python function to generate fibonacci numbers:
def fib(n):
return ((1+math.sqrt(5))**n - (1-math.sqrt(5))**n)/(2**n*math.sqrt(5))
I can feed the fib function numbers up to 700, where it starts to
OverflowError: (34, 'Numerical result out of range')
Do I need to use a special type like long to get around this?
The problem is that you’re using doubles to calculate the value and the doubles are overflowing.
Doubles give exact solutions only to about the 85th Fibonacci number.
If you want a fast and accurate calculation you’re better off using an algorithm based on a better recurrence relationship, and using python bignum integers.
In particular you can use:
Or the equivalent matrix exponentiation formula (excuse the ugly formatting)
Both of these result in algorithms that require
O(log(N))calculations rather thanO(N).Here’s a complete solution in pseudo-code
If you do want to perform your calculations using doubles and the explicit formulae, then the formulae can be tweaked to give something faster that doesn’t overflow until about the 1500th fibonacci number, and remains the same accuracy as your version. IIRC it is: