【问题标题】:Fibonnacci numbers less than set value斐波那契数小于设定值
【发布时间】: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) &lt; m
  • while max(total) &gt; m: 一开始不是真的。而且你的 fib 函数并不是在这里计算 fib 值的最佳选择!
  • 维基百科什么是最好的fib函数。
  • 警告:由于精度有限,您的函数在 n=71 时停止工作。当答案为 308061521170129 时,您的 Fib 返回 308061521170130.0。

标签: python python-3.x fibonacci


【解决方案1】:
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 total[-1] < m:
        total.append(Fib(count))
        count = count + 1
    return total

您必须检查总长度是否小于 m。

【讨论】:

  • Than 返回一个斐波那契数列,即输入的长度。我想要一个函数,它可以产生高达某个值的斐波那契数
  • @phighter 随心所欲地修改它:)
猜你喜欢
  • 1970-01-01
  • 2015-06-05
  • 2014-05-23
  • 2014-05-03
  • 1970-01-01
  • 2020-10-18
  • 2015-06-26
相关资源
最近更新 更多