Generate Fibonacci numbers with Python
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.
1 2 3 4 5 | 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,
1 2 | 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 liked this post, these other posts might also be interesting to you:
Category: Mathematics, Python | Comment (RSS) | Trackback

KNizam:
tak letak shoutbox ke eh ? hehe
July 31, 2008, 8:25 pmselinap.com:
Nak letak mana bagus?
July 31, 2008, 9:43 pmEven-valued Fibonacci terms summation | Selinap:
[...] AboutContactArchives « Generate Fibonacci numbers with Python [...]
August 1, 2008, 1:03 amFail:
Actually, that should be:
August 1, 2008, 9:49 pma, b = 1, 0
Otherwise it won’t emit the first two, 0 and 1.
selinap.com:
If you read carefully, I have stated “By starting with 1 and 2, the first 10 terms will be: …”.
August 2, 2008, 7:41 am