gpt4 book ai didi

python - 斐波那契常数倒数

转载 作者:太空宇宙 更新时间:2023-11-03 18:55:38 25 4
gpt4 key购买 nike

我正在开发一个计算斐波那契常数倒数(斐波那契数的无限总和)的程序。它计算每一项直到其误差:

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

最佳答案

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

关于python - 斐波那契常数倒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17326308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com