1st of all, I'm trying to understand why I'm getting an overflow error. the first function "fibGen" works fine unless I give it an insanely large nth Fibonacci term.
#the golden ration function
def fibGen(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print('{i:3}: {v:3}'.format(i=number, v=round(val)))
The second function "elemFib" will give me the correct answer but then errors out if number is over 1500.
#the find element < Max number function
def elemFib(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
if val < num:
print('Fib({}): {}'.format(number, round(val)))
lastly, the function "pythonic" works like the "elemFib" function and does not give me an error code for even a very large number, why is that? Also, I'm trying to get it to print the Fibonacci numbers like the first function "fibGen" but can't get it to work like that.
#Pythonic way
def pythonic(num):
a, b = 0,1
while a < num:
print(a, sep=" ", end=" ")
a, b = b, a+b
My complete code for your review:
import math
import time
#create the golden Ratio formula
golden_ratio = (1 + math.sqrt(5)) / 2
#the timer function
def clockTime(start_time):
print('\nRun Time:', time.time() - start_time)
#the golden ration function
def fibGen(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print('{i:3}: {v:3}'.format(i=number, v=round(val)))
#the find element < Max number function
def elemFib(num):
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
if val < num:
print('Fib({}): {}'.format(number, round(val)))
#Pythonic way
def pythonic(num):
a, b = 0,1
while a < num:
print(a, sep=" ", end=" ")
a, b = b, a+b
#display the Main Menu
def dispMenu():
print('---------------------Fibonacci Series ------------------\n')
print('(A) Print Fibonacci numbers to the nth term')
print('(B) Print Fibonacci numbers until element is less than Max number')
print('(C) pythonic print')
print('(Q) Quit the program\n')
def main():
# set boolean control variable for loop
loop = True
#Create while loop for menu
while loop:
#Display the menu
dispMenu()
#Get user's input
#choice = (input('Please make a selection: '))
#Get user's input
choice = input('Please make a selection: ').upper()
#Perform the selected action
if choice == 'A':
num = int(input("How many Fibonacci numbers should I print? "))
start_time = time.time()
fibGen(num)
clockTime(start_time)
elif choice == 'B':
num = int(input("the element should be less than? "))
start_time = time.time()
elemFib(num)
clockTime(start_time)
elif choice == 'C':
num = int(input('Pythonic Fibonacci series to the nth term? '))
start_time = time.time()
pythonic(num)
clockTime(start_time)
elif choice == 'Q':
print('\nExiting program, Thank you and Goodbye')
loop = False
else:
print('\nInvalid selection, try again\n')
main()