NumPy 使用Binet公式的斐波那契数列
我们所有人都熟悉斐波那契数列。序列中的每个数字都是它前面两个数字的总和。所以,这个序列是:0, 1, 1, 2, 3, 5, 8, 13, 21, 34…… 在本教程中,我们将使用NumPy借助Binet公式实现同样的内容。
Binet Formula
n “是与斐波那契数列的前’n’个数字有关的参数。在第一个例子中,我们将找出斐波那契数列的前10个数字(n = 10),然后我们从用户那里获得参数’n’,并产生相应的结果。
注:我们忽略了斐波那契数列的第一个元素(0)。
例子1:要找到前10个斐波那契数。
import numpy as np
# We are creating an array contains n = 10 elements
# for getting first 10 Fibonacci numbers
a = np.arange(1, 11)
lengthA = len(a)
# splitting of terms for easiness
sqrtFive = np.sqrt(5)
alpha = (1 + sqrtFive) / 2
beta = (1 - sqrtFive) / 2
# Implementation of formula
# np.rint is used for rounding off to integer
Fn = np.rint(((alpha ** a) - (beta ** a)) / (sqrtFive))
print("The first {} numbers of Fibonacci series are {} . ".format(lengthA, Fn))
输出 :
斐波那契数列的前10个数字是[ 1. 1. 2. 3. 5. 8. 13. 21. 34. 55. ] 。
例子2 :要找到前’n’个斐波那契数.
import numpy as np
# We are creating an array contains n elements
# for getting first 'n' Fibonacci numbers
fNumber = int(input("Enter the value of n + 1'th number : "))
a = np.arange(1, fNumber)
length_a = len(a)
# splitting of terms for easiness
sqrt_five = np.sqrt(5)
alpha = (1 + sqrt_five) / 2
beta = (1 - sqrt_five) / 2
# Implementation of formula
# np.rint is used for rounding off to integer
Fn = np.rint(((alpha ** a) - (beta ** a)) / (sqrt_five))
print("The first {} numbers of Fibonacci series are {} . ".format(length_a, Fn))
输出 :
# Here user input was 10
Enter the value of n+1'th number :10
The first 9 numbers of Fibonacci series are [ 1. 1. 2. 3. 5. 8. 13. 21. 34.] .