我正在开发一个计算倒数斐波那契常数(斐波那契数的无限总和)的程序。它计算每个项直到它的错误:
我有一个程序,但它只能达到 1474 个术语,我需要达到大约 10000 个术语。它返回一个错误:
Traceback (most recent call last):
File "/Users/jaddvirji/Desktop/PapaTechChallenges/Challenge2/Part1/main.py", line 23, in <module>
curf.write(str(Decimal(fibConstant(x))))
File "/Users/jaddvirji/Desktop/PapaTechChallenges/Challenge2/Part1/main.py", line 18, in fibConstant
return (1.0 / fib(n)) + fibConstant(n - 1.0)
File "/Users/jaddvirji/Desktop/PapaTechChallenges/Challenge2/Part1/main.py", line 12, in fib
return long(((phi**n) - (1-phi)**n) / 5**0.5)
OverflowError: (34, 'Result too large')
我的代码是:
#!/usr/bin/env python
print "(C) COPYRIGHT JADD VIRJI 2013. ALL RIGHTS RESERVED."
from decimal import *
import time as t
import sys
sys.setrecursionlimit(10000)
phi = (1+(5**0.5))/2
def fib(n):
return long(((phi**n) - (1-phi)**n) / 5**0.5)
def fibConstant(n):
if(n == 1):
return (1.0 / fib(n))
else:
return (1.0 / fib(n)) + fibConstant(n - 1.0)
x = 1
while True:
curf = open(str(x)+" term.txt","w")
curf.write(str(Decimal(fibConstant(x))))
curf.close()
x = x+1
print Decimal(x)
print "DONE. THANKS FOR USING."
此外,上述大约 200 个术语的每个结果都是相同的(并且是错误的。)
有谁知道如何解决这些问题?
编辑:我有一种感觉,大约 200 个术语之后的问题是由于 Binet Fibonacci 计算的浮点错误。如何使这些小数永远存在?