【发布时间】:2012-08-19 16:34:59
【问题描述】:
我正在计算第 n 个斐波那契数,使用 (a) 线性方法,以及 (b) this 表达式
Python 代码:
'Different implementations for computing the n-th fibonacci number'
def lfib(n):
'Find the n-th fibonacci number iteratively'
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return a
def efib(n):
'Compute the n-th fibonacci number using the formulae'
from math import sqrt, floor
x = (1 + sqrt(5))/2
return long(floor((x**n)/sqrt(5) + 0.5))
if __name__ == '__main__':
for i in range(60,80):
if lfib(i) != efib(i):
print i, "lfib:", lfib(i)
print " efib:", efib(i)
对于 n > 71,我看到这两个函数返回不同的值。
这是因为 efib() 中涉及浮点运算吗? 如果是这样,是否建议使用matrix form 计算数字?
【问题讨论】:
标签: python algorithm fibonacci