Browse Source

Worked on three different recursive ways to calculate fibonacci and graph its time complexity.

pull/2/head
jrtechs 6 years ago
parent
commit
c2bf646732
6 changed files with 81 additions and 0 deletions
  1. BIN
      fibonacci/FibPower.png
  2. BIN
      fibonacci/FibPowerBigPicture.png
  3. +49
    -0
      fibonacci/Fibonacci.py
  4. BIN
      fibonacci/Iterative.png
  5. +32
    -0
      fibonacci/PlotTimeComplexity.py
  6. BIN
      fibonacci/RecursiveDefinition.png

BIN
fibonacci/FibPower.png View File

Before After
Width: 640  |  Height: 480  |  Size: 38 KiB

BIN
fibonacci/FibPowerBigPicture.png View File

Before After
Width: 640  |  Height: 480  |  Size: 31 KiB

+ 49
- 0
fibonacci/Fibonacci.py View File

@ -0,0 +1,49 @@
def fib(n):
if n == 0 or n == 1:
return n
return fib(n-1) + fib(n-2)
def fibHelper(n, a, b):
if n == 0:
return a
elif n == 1:
return b
return fibHelper(n-1, b, a+b)
def fibIterative(n):
return fibHelper(n, 0, 1)
def multiply(a,b):
product = [0,0,0]
product[0] = a[0]*b[0] + a[1]*b[1]
product[1] = a[0]*b[1] + a[1]*b[2]
product[2] = a[1]*b[1] + a[2]*b[2]
return product
def power(l, k):
if k == 1:
return l
temp = power(l, k//2)
if k%2 == 0:
return multiply(temp, temp)
else:
return multiply(l, multiply(temp, temp))
def fibPower(n):
l = [1,1,0]
return power(l, n)[1]
"""
Makes sure that other programs don't execute the main
"""
if __name__ == '__main__':
try:
print(fib(30))
except KeyboardInterrupt:
exit()

BIN
fibonacci/Iterative.png View File

Before After
Width: 640  |  Height: 480  |  Size: 26 KiB

+ 32
- 0
fibonacci/PlotTimeComplexity.py View File

@ -0,0 +1,32 @@
import matplotlib.pyplot as plt
import time
from fibonacci import Fibonacci as fib
def measureTime(n):
total = 0
for i in range(0, 200):
start_time = time.time()
fib.fibPower(n)
end_time = time.time()
total += end_time - start_time
return total/200
def generateData():
time = []
input = []
for i in range(1, 2000, 20):
input.append(i)
time.append(measureTime(i))
return input, time
data = generateData()
plt.plot(data[0], data[1])
plt.xlabel('Fibonacci Term')
plt.ylabel('Seconds')
plt.show()

BIN
fibonacci/RecursiveDefinition.png View File

Before After
Width: 640  |  Height: 480  |  Size: 19 KiB

Loading…
Cancel
Save