Fibonacci的Python打印不起作用

时间:2014-09-07 15:24:21

标签: python math cmath

我试图打印斐波那契序列Benet's formula,但我的价值观并不正确。我在这里错过了什么吗?

import math

def F(n):
    return ((1+math.sqrt(5))**n-(1-math.sqrt(5))**n)/(2**n*math.sqrt(5))

for x in range(0, 100):
    print(F(x))

我得到的结果是:

0.0
1.0
1.0
2.0
3.0000000000000004
5.000000000000001
8.000000000000002 --- start's going wrong here
13.000000000000002
21.000000000000004
...

必须与精确度有关。但是,使用cmath代替math似乎也无济于事。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:3)

如果您担心它,请将结果作为int返回,这只是一个如何表示浮点数的工件。

import math

def F(n):
    return int(((1+math.sqrt(5))**n-(1-math.sqrt(5))**n)/(2**n*math.sqrt(5)))

for x in range(0, 15):
    print F(x)

输出

0
1
1
2
3
5
8
13
21
34
55
89
144
233
377