斐波那契数列计算_计算斐波那契数列的最快方法

斐波那契数列计算

What is the Fibonacci sequence? It’s easy to define: the first element is 1, the second is 2, and the following elements are the sum of the two previous ones: the 3rd element is 3 (2 +1), the 4th is 5 (3+2), the 5th is 8 (5+3) etc.

斐波那契数列是什么? 定义起来很容易:第一个元素是1,第二个元素是2,以下元素是前两个元素的和:第三个元素是3(2 +1),第四个元素是5(3 + 2),第五是8(5 + 3),依此类推。

Tonight on the Python Discord channel, a user came up with a challenge: find a faster Python implementation to compute the elements of the Fibonacci sequence than this one:

今晚在Python Discord频道上,一个用户提出了一个挑战:找到比该方法更快的Python实现来计算Fibonacci序列的元素:

Challenge accepted. I already knew there is a closed form (direct formula) to compute the Fibonacci values, so I thought it would be enough to apply it directly to beat this implementation… but it was not that easy

接受挑战。 我已经知道可以使用一个封闭的形式(直接公式)来计算斐波那契值,所以我认为直接应用它来击败该实现就足够了……但是那并不容易

比内公式 (Binet Formula)

There is a closed form called Binet formula, proven here to compute the n-th Fibonacci value. Translated in Python (with numpy), it gives:

有一个称为Binet公式的封闭形式, 在这里已被证明可以计算第n个斐波那契值。 用Python(带numpy)翻译,它提供:

import numpy as npdef fibonacci(n):
return np.floor(1 / np.sqrt(5) * (((1 + np.sqrt(5)) / 2) ** n - ((1 - np.sqrt(5)) / 2) ** n))

Perfect. Note also the golden ratio in the formula. What is the problem with this? Let’s try it out:

完善。 注意公式中的黄金比例 。 这是什么问题? 让我们尝试一下:

fibonacci(1500)/home/manuel/.local/lib/python3.6/site-packa
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值