简体   繁体   English

倒数斐波那契常数

[英]Reciprocal Fibonacci Constant

I am working on a program that calculates the Reciprocal Fibonacci Constant (the infinite summation of the Fibonacci numbers.) It calculates every term upto it's error: 我正在开发一个程序,该程序计算倒数斐波那契常数(斐波那契数的无穷总和。)它计算每个项直到错误为止:

I have an program but it only goes to 1474 terms and I need to get to about 10000 terms. 我有一个程序,但只用了1474个学期,我需要达到10000个学期。 It returns an error: 它返回一个错误:

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')

And my code is: 我的代码是:

#!/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."

Also, Every result from about 200 terms above is the same (and wrong.) 此外,上述大约200个字词的每个结果都是相同的(而且是错误的)。

Does anybody know how to fix these problems? 有人知道如何解决这些问题吗?

EDIT: I have a feeling that the problems after ~200 terms are because of floating point errors with the Binet Fibonacci calculation. 编辑:我感觉〜200个词后的问题是由于Binet Fibonacci计算中的浮点错误。 How do I make these decimals go on forever? 如何使这些小数位数永远持续下去?

Try storing the values of fibConstant in a list. 尝试将fibConstant的值存储在列表中。 Then for each subsequent calculation, you only need to call the last value of the list instead of recalculating. 然后,对于每个后续的计算,您只需要调用列表的最后一个值即可,而无需重新计算。 For example: 例如:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM