我计算使用 (a)一种线性方法的第n个Fibonacci数第n个斐波纳契数,和 (b)中表达this计算使用该公式在python
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来计算数字吗?
没有必要建立在内存中的列表,包括'.append'。你可以使用两个变量 - 参见OP的'lfib'的定义。 – peterhurford