斐波那契数列计算
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