倒数斐波纳契常数

时间:2013-06-26 17:06:36

标签: python math

我正在研究一个计算倒数Fibonacci常数的程序(Fibonacci数的无限求和。)它计算每个项到它的错误:

我有一个程序,但它只有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计算的浮点错误。如何使这些小数值永远持续下去?

1 个答案:

答案 0 :(得分:1)

尝试将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)