1

I'm trying to make a fibonacci number generator that stops at a given amount, but it usually goes past the amount. What am I doing wrong?

#Fibonacci number generator
a=0
b=1
print("Fibonacci number generator.")
stopNumber=input("How high do you want to go? If you want to go forever, put n.")
print(1)
while stopNumber=="n":
        a=a+b
        b=b+a
        print(a)
        print(b)
else:
    while int(stopNumber) > a or int(stopNumber) > b:
        a=a+b
        b=b+a
        print(a)
        print(b)
JRickert
  • 23
  • 3
  • Could you show us some output from this? If you enter 20, what do you get? – wdh Nov 07 '13 at 14:20
  • 1
    Pretty weird fibbonacci generator. Why are you doing `a=a+b` and `b=b+a` in single step? It should be something like `prev, current = current, prev + current` – J0HN Nov 07 '13 at 14:21

7 Answers7

1

The reason you are getting some higher values is because you are having a = a+b and b = b+a in a single loop. So when you are checking the values in while int(stopNumber) > a or int(stopNumber) > b: you get True and enter the loop but a = a+b and b = b+a can make the value of a and b greater than stopNumber and since you are printing it without checking it, you are getting some higher values. You should increment only once in the loop and if you write the print statement just after the while loop you will not get correct values

prev = 0                             
curr = 1
print("Fibonacci number generator.")
stopNumber = input("How high do you want to go? If you want to go forever, put n.")
if stopNumber == 'n':                    
    print(curr)                     
    curr = prev + curr
    prev = curr
else:
    while curr<stopNumber:
        print(curr)
        curr = prev + curr
        prev = curr

Note: The code will run forever if the input is n.

Ankur Ankan
  • 2,953
  • 2
  • 23
  • 38
  • Never ever use the input statement, this is a call for an attack. and the algorithm should run forever if the input is 'n' not stop after one iteration. – Samy Arous Nov 07 '13 at 14:31
  • @lcfseth: Yes I know it will run forever if the input is `n`. I just wanted to explain why he is getting larger values than `stopNumber` – Ankur Ankan Nov 07 '13 at 14:34
1

The same, working and using a little smarter techniques:

# returns generator
def fib(stop):
    prev, current = 0, 1
    while current < stop:  # a little hack here - python is ok comparing ints to floats
        yield current
        # multiple assginment - operands on the left are "frozen" just before theis instruction
        prev, current = current, prev + current 

# note inf - float('inf') results in "positive infinity" which is an appropriate math concept for "forever"
stop = float(input("How high do you want to go? If you want to go forever, put inf."))

for f in fib(stop):
    print (f)

Note: please don't try doing list(fib(float('inf'))) :)

J0HN
  • 26,063
  • 5
  • 54
  • 85
  • One little adjustment if I may. make stop optional and equal to None by default. if stop is not set, the while loop should run forever – Samy Arous Nov 07 '13 at 14:33
0

You do the check if stopNumber > a or b, then you increment a and b, printing them. If you only wanted to print them if they were <= stopNumber than do something like this:

#Fibonacci number generator
a=0
b=1
print("Fibonacci number generator.")
stopNumber=input("How high do you want to go? If you want to go forever, put n.")
print(1)
while stopNumber=="n":
        a=a+b
        b=b+a
        print(a)
        print(b)
else:
    while True:
        a = a+b
        b = b+a
        if int(stopNumber) >= a:
           print(a)
        if int(stopNumber) >= b:
           print(b)
        else:
          break
Tom Swifty
  • 2,864
  • 2
  • 16
  • 25
0

Using your code:

#Fibonacci number generator
a=0
b=1
print("Fibonacci number generator.")
stopNumber=input("How high do you want to go? If you want to go forever, put n.")
print(1)
while stopNumber=="n" or int(stopNumber) > a+b:
    a, b = b, a+b
    print(b)
0

The second "while" loop keeps running always either "a" OR "b" is lower than "stopNumber". Therefore, the loop continues to run until BOTH "a" and "b" are greater than "stopNumber". In consequence, when "b" is greater than "stopLimit" but "a" is still lower than "stopLimit" the loop keeps running. So the first fix to apply is to change the "or" condition by an "and" one.

You are only checking that the condition applies before the sums. Then, by the moment that the sums are done their results may be greater than "stopLimit"; and that is what you print. To fix this, you can add an "if" statement to verify that the sum results are still below "stopNumber".

This is how the code looks with these fixes:

#Fibonacci number generator
a=0
b=1
print("Fibonacci number generator.")
stopNumber=input("How high do you want to go? If you want to go forever, put n.")
print(1)
while stopNumber=="n":
        a=a+b
        b=b+a
        print(a)
        print(b)
else:
    while int(stopNumber) > a and int(stopNumber) > b:
        a=a+b
        b=b+a
        if int(stopNumber) > a:
            print(a)
        if int(stopNumber) > b:
            print(b)
Ricardo Alejos
  • 402
  • 4
  • 9
0
 #This is a simple yet efficient program using recursion:

def fibonacci_rec(a, b):
    if a >= 0 and b > 0 or a > 0 and b >= 0:
        s = [a, b]
        while a+b <= 1000: #can set any upper boundary  
            f = a+b
            a = b
            b = f
            s.append(f)
            fibonacci_rec(a, b)
        return s
    else:
        return 'Invalid'

print(fibonacci_rec(1, 1))  # You can set any value of a and b, as you like and no need to iterate in here, just call function once and it does the iteration for you! 
-1
def fib(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fib(n-1) + fib(n-2)

print("Fibonacci number generator.")
stopNumber=input("How high do you want to go? If you want to go forever, put n.")
if stopNumber == 'n':
    i=1
    while True:
        print 'Fibonacci #{0}: {1}'.format(i, fib(i))
        i=i+1
else:
    for i in range(1,int(n)):
        print 'Fibonacci #{0}: {1}'.format(i, fib(i))
Lorcan O'Neill
  • 3,303
  • 1
  • 25
  • 24
  • The recursive fibonacci version is easy to understand but for complexity issues, should never used in real code. – Samy Arous Nov 07 '13 at 14:28