猿问

倒数斐波那契常数

我正在开发一个程序,该程序计算倒数斐波那契常数(斐波那契数的无穷总和。)它计算每个项直到错误为止:


我有一个程序,但只用了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个术语的每个结果都是相同的(而且是错误的)。


有人知道如何解决这些问题吗?


狐的传说
浏览 139回答 1
1回答

守候你守候我

尝试将的值存储fibConstant在列表中。然后,对于每个后续的计算,您只需要调用列表的最后一个值即可,而无需重新计算。例如:from math import sqrtphi = (1 + sqrt(5)) / 2.def fib(n):&nbsp; &nbsp; return (phi**n - (1-phi)**n) / sqrt(5)fib_constant_list = [1./fib(1)]def fib_constant(n):&nbsp; &nbsp; new_fib_c = (1./fib(n) + fib_constant_list[-1])&nbsp; &nbsp; fib_constant_list.append(new_fib_c)&nbsp; &nbsp; return new_fib_cn = 2N_MAX = 1000while n < N_MAX:&nbsp; &nbsp; &nbsp;print fib_constant(n)
随时随地看视频慕课网APP

相关分类

Python
我要回答