Generate Fibonacci numbers with Python

Thursday, July 31st, 2008
Advertisement

Subscribe.
Enter your email:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

Mathematically, we write it as:
F(n) = F(n) + F(n-1)

This can easily be done in Python, using generators.

def Fibonacci(n):
    a, b = 1, 1
    while b < n:
        yield b
        a, b = b, a + b

To print all the Fibonacci numbers less than 4000000,

for i in Fibonacci(4000000):
    print i,

Output:

>>> 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578

If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

Creates the exact copy of your hard disk and allows you to instantly restore the entire machine.
New Acronis True Image Home 2010 is the most reliable and easy in use backup solution. Now with online backup option!
15% Discount Code: FMAATIH2010

What else?

Like this article? Share it

 Digg  del.icio.us  TwitThis  Facebook  Reddit  StumbleUpon

5 Responses to “Generate Fibonacci numbers with Python”

  1. KNizam says:

    tak letak shoutbox ke eh ? hehe :roll:

  2. Selinap says:

    Nak letak mana bagus?

  3. [...] AboutContactArchives « Generate Fibonacci numbers with Python [...]

  4. Fail says:

    Actually, that should be:
    a, b = 1, 0
    Otherwise it won’t emit the first two, 0 and 1.

  5. Selinap says:

    If you read carefully, I have stated “By starting with 1 and 2, the first 10 terms will be: …”.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>