我正在開發一個程序,該程序計算倒數斐波那契常數(斐波那契數的無窮總和。)它計算每個項直到錯誤為止:我有一個程序,但只用了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
提交
取消