我正在开发一个程序,该程序计算倒数斐波那契常数(斐波那契数的无穷总和。)它计算每个项直到错误为止:
我有一个程序,但只用了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个术语的每个结果都是相同的(而且是错误的)。
有人知道如何解决这些问题吗?
守候你守候我
相关分类