我正在开发一个程序,该程序计算倒数斐波那契常数(斐波那契数的无穷总和。)它计算每个项直到错误为止:我有一个程序,但只用了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 fibConstantreturn (1.0 / fib(n)) + fibConstant(n - 1.0)File "/Users/jaddvirji/Desktop/PapaTechChallenges/Challenge2/Part1/main.py", line 12, in fibreturn long(((phi**n) - (1-phi)**n) / 5**0.5)OverflowError: (34, 'Result too large')我的代码是:#!/usr/bin/env pythonprint "(C) COPYRIGHT JADD VIRJI 2013. ALL RIGHTS RESERVED."from decimal import *import time as timport syssys.setrecursionlimit(10000)phi = (1+(5**0.5))/2def 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 = 1while 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个术语的每个结果都是相同的(而且是错误的)。有人知道如何解决这些问题吗?
1 回答

守候你守候我
TA贡献1802条经验 获得超10个赞
尝试将的值存储fibConstant在列表中。然后,对于每个后续的计算,您只需要调用列表的最后一个值即可,而无需重新计算。例如:
from math import sqrt
phi = (1 + sqrt(5)) / 2.
def fib(n):
return (phi**n - (1-phi)**n) / sqrt(5)
fib_constant_list = [1./fib(1)]
def fib_constant(n):
new_fib_c = (1./fib(n) + fib_constant_list[-1])
fib_constant_list.append(new_fib_c)
return new_fib_c
n = 2
N_MAX = 1000
while n < N_MAX:
print fib_constant(n)
添加回答
举报
0/150
提交
取消