I tried two algorithms for Fibonacci series and compare the speed.
The first one is by powers of matrices through Numpy (I also wrote my own function but seems numpy is faster).
import numpy as np
import time
def fibonacci_power(n):
F=np.matrix('1,1;1,0')
Fn=F**(n-1)
return Fn[0,0]
The second is dynamic programming with a shortened memory.
def fibonacci_mem(n):
f=[0, 1]
if n<=1:
return f[n]
for i in range(2, n+1):
temp=f[1]
f[1]=f[1]+f[0]
f[0]=temp
return f[1]
The time complexity of the first one is O(log n) and the second is O(n). So for larger n, the first one should be faster.
I compare their speed in the following:
def main():
n=90
start=time.time()
f1=fibonacci_power(n)
f1_time=time.time()-start
print('Power/Numpy result: '+str(f1)+' time: '+str(f1_time))
start=time.time()
f3=fibonacci_mem(n)
f3_time=time.time()-start
print('Memory result: '+str(f3)+' time: '+str(f3_time))
The result is:
Power/Numpy result: 2880067194370816120 time: 0.00021696090698242188
Memory result: 2880067194370816120 time: 4.410743713378906e-05
Am I comparing their speed in the right way? If yes, can anyone explain why the second is faster? Thanks.