【发布时间】:2015-06-22 19:36:38
【问题描述】:
为什么这段代码没有生成小于设定值的斐波那契数。
from math import sqrt
def Fib(n):
return round(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)))
def Fiblessthan(m):
total = [0]
count = 1
while max(total) < m:
total.append(Fib(count))
count = count + 1
例如,我不能打印所有小于 4000000 的斐波那契数。这是处理这个问题的正确方法吗?
【问题讨论】:
-
它的作用是什么?
-
不应该是
max(total) < m -
while max(total) > m:一开始不是真的。而且你的 fib 函数并不是在这里计算 fib 值的最佳选择! -
维基百科什么是最好的fib函数。
-
警告:由于精度有限,您的函数在 n=71 时停止工作。当答案为 308061521170129 时,您的
Fib返回 308061521170130.0。
标签: python python-3.x fibonacci