问题
I have seen Fibonacci has direct formula with this (Phi^n)/√5
while I am getting results in same time but accurate result not approximate with something I managed to write:
for r = 0 to 2 Sum [(n-r)!/((n-2r)!r!)]
(!
is the symbol for factorial ):
def fr(n, p):
# (n-r)!/((n-2r)!r!)
r = int(n / p)
n_f = 0
for j in range(1, r + 1):
t_f = 1
r_f = factorial(j)
i = (n - j)
while i > (n - (2 * j)):
t_f = t_f * i
i = i - 1
n_f = n_f + t_f / r_f
return n_f + 1
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
so for 12 we can do fr(11, 2)
also (Phi12)/√5 = 144.0013888754932
rounds to Fib(12) =144
I don't understand why (n-r)!/((n-2r)!r!)
is fast
回答1:
Binet's formula for the nth Fibonacci number is as follows:
def binet(n):
phi = (1 + 5**.5) / 2
psi = (1 - 5**.5) / 2
return (phi**n - psi**n) / 5**.5
This formula is mathematically exact, but in practice it is subject to floating point error. The term psi**n converges rapidly to zero as n increases, so it can be omitted when n is large. This yields your approximate formula.
Binet's formula is very fast. On my machine, it computes the 1000th Fibonacci number in about 400 nanoseconds.
In [21]: %timeit binet(1000)
426 ns ± 24.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
The binomial sum formula for Fibonacci numbers is very interesting. It says that Fibonacci numbers are sums along shallow diagonals of Pascal's triangle, as shown in this figure.
This formula works because each diagonal is the sum of the two previous diagonals, just as every term in the Fibonacci sequence is the sum of the two previous terms. For example, the ninth and tenth diagonals can be added to obtain the eleventh diagonal.
1 + 7 + 15 + 10 + 1 = 34
1 + 8 + 21 + 20 + 5 = 55
-----------------------------
1 + 9 + 28 + 35 + 15 + 1 = 89
However, this formula is not fast at all. It seems fast because computers can perform millions of calculations per second. My machine needs 84 ms to calculate the 1000th Fibonacci number using your code. This is 200,000 times longer than it takes using Binet's formula.
In [22]: %timeit fr(1001, 2)
84 ms ± 875 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
来源:https://stackoverflow.com/questions/50622088/fibonacci-direct-calculation-formula