用python中的公式计算n个fibonacci数

用python中的公式计算n个fibonacci数,python,algorithm,fibonacci,Python,Algorithm,Fibonacci,我正在使用 (a) 线性方法,以及 (b) 表情 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 efi

我正在使用 (a) 线性方法,以及 (b) 表情

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()中涉及浮点运算吗?
如果是这样,那么是否建议使用?您确实看到了舍入错误

矩阵形式是更精确、更快的算法。列出了一个很好的实现,但也列出了以下基于Lucas数的算法:

def powLF(n):
    if n == 1:     return (1, 1)
    L, F = powLF(n//2)
    L, F = (L**2 + 5*F**2) >> 1, L*F
    if n & 1:
        return ((L + 5*F)>>1, (L + F) >>1)
    else:
        return (L, F)

def fib(n):
    if n & 1:
        return powLF(n)[1]
    else:
        L, F = powLF(n // 2)
        return L * F
看看矩阵方法的良好分析

上述算法和矩阵方法都具有Θ(lgn)复杂性,就像您使用的简单递归平方法一样,但没有舍入问题。Lucas数法的固定成本最低,使其成为更快的算法(大约是矩阵法的两倍):

这是因为efib()中涉及浮点运算吗

是的。在
efib
中,您有

>>> log(x**72)/log(2)
49.98541778140445

在x86-64硬件上,您的运行非常接近边缘。

我有一个非常简单的纯python代码

def fibonum(n):   # Give the nth fibonacci number
    x=[0,1]
    for i in range(2,n):
        x.append(x[i-2]+x[i-1])
    print(x[n-1])

无需使用
.append
在内存中建立列表。您可以只使用两个变量——请参见OP中的
lfib
的定义。
def fibonum(n):   # Give the nth fibonacci number
    x=[0,1]
    for i in range(2,n):
        x.append(x[i-2]+x[i-1])
    print(x[n-1])