Understanding Fibonacci Series in Python, With Examples

Sashkin / Shutterstock.com

The Fibonacci exercise is a coding exercise where the programmer creates a program that produces a number of integers from the Fibonacci series when you input a real number. Since the program must produce at least one integer, naturally, negative numbers cannot be used as inputs, and you ll be creating a code statement to produce an error if one is put into the program. The Fibonacci exercise can be performed in any coding language, but we ll focus on Python in this article.

What Is the Fibonacci Series? How Is It Calculated?

The Fibonacci Series is a series of numbers. It begins as follows and continues indefinitely:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

In the Fibonacci Series, the next number is calculated by adding the two most recent integers together, starting at 0 and 1. So, 0+1=1, 1+1=2, 1+2=3, 2+3=5 and so on. As we stated, the series continues indefinitely. So you can continue to add numbers together in theFibonacci sequenceas much as you like. Assuming your computer could handle it, a Fibonacci program could produce an indefinite number of outputs.

Combining the numbers in the Fibonacci series as squares makes a pretty-looking spiral often called the Golden Ratio. As the series progresses, this relationship between the Fibonacci numbers converges on Phi, which has a value of 1.618. Phi is the Golden Ratio.

Understanding Fibonacci series Python
The pattern of seeds in a sunflower follows the Fibonacci sequence.

Africa Studio/Shutterstock.com

Simply put, when we take any two successive Fibonacci numbers and turn them into a ratio, their ratio will be very close to the value of Phi the Golden Ratio and the numbers approach Phi as you continue through the series.

Examples of the Fibonacci Numbers Expressed as Ratios

2 3 1.5
3 5 1.666
5 8 1.6
8 13 1.625

The Fibonacci series is formulaic and can be expressed with the following formula:

Xn= Xn-1+ Xn-2

Who Developed the Fibonacci Series?

Leonardo Bonacci, also known as Leonard de Pisa and Leonardo Bigollo Pisano, posed the Fibonacci sequence. Bonacci proposed it as a solution to the problem of rabbit populations and breeding in his manuscriptLiber Abaci. Unfortunately, while the manuscript was published in 1202, the oldest version of the manuscript we can find is from 1228.

Liber Abacitackled many topics, including the modus Indorum (method of Indians), now known as the Hindu-Arabic Numeral System. The Hindu-Arabic System uses ten digits, a zero, and positional notation, all of which are used in calculating the Fibonacci sequence.

How to Write a Fibonacci Series Exercise in Python

Writing a Fibonacci series exercise is a relatively straightforward exercise. It s one of the first exercises you ll do as you get comfortable with any programming language. There are several ways to write a Fibonacci exercise, but we ll focus on and explain the most efficient ways to do so (most novice coders would write a version of the program that works but is less efficient.)

Using Recursion

# Function for nth Fibonacci number
def Fibonacci(n):
    # Check if input is less than 0 then it will
    # print incorrect input
    if n 

Using recursion, we can write a simpleprogram to output a Fibonacci numberwhen provided with its position in the sequence. So, inputting a 5 will output thefifthnumber in the Fibonacci sequence. We ll start by defining the function Fibonacci with the parameter n.

Then we want the program to check if the input is less than 0, which is an invalid input. By telling the program if n

We also need the program to correctly print the first two numbers of the Fibonacci sequence, which the formula can t determine. So we ll add a statement so that when the input is 1 or 2, the program will print a 1 to ensure the computer doesn t get tripped up.

Finally, we ll put the formula in. Using the subscript, we can tell the computer which numbers to use in the formula based on their position in the Fibonacci sequence. We ve defined the first three, and the program will calculate the remaining numbers to return your answer.

Using the Cache to Store Previous Results

# Function for nth fibonacci
# number - Dynamic Programming
# Taking 1st two fibonacci numbers as 0 and 1
FibArray = [0, 1]
def fibonacci(n):
    # Check is n is less
    # than 0
    if n 

First, we ll start by defining an Array with the first two values in the Fibonacci sequence, 0 and 1. Then we ll do the same thing as the code above and check if the input is less than 0 and have the program print an Invalid Entry if it is.

Now we need the len function to check the current length of FibArray. Since FibArray is just that, an Array, every calculated number in the sequence that is, every number calculated up to the highest value you ve input during this session will be stored in the cache and can be retrieved without the program having to recalculate all the numbers before it.

After that, we ll have the program update the values in the Arrayif the input is greater than the current length of the Arrayand print the newly calculated value.

Using Backtracking to Store the Previous Results

# Function for nth fibonacci
# number - Space Optimisation
# Taking 1st two fibonacci numbers as 0 and 1
def fibonacci(n):
    a = 0
    b = 1
    # Check is n is less
    # than 0
    if n 

This code uses the memo function to store the results of the memorandum in the code, allowing the code to pull from what is essentially a cache for the results of the method it s attached to. This allows the code to pull from the memorandum to return new numbers instead of recalculating the result.

The code then defines that if the input is less than 0 it will return Invalid Entry. It also defines the first number in the sequence as 1. Next, the code will check to see if the position value, n, you entered is already stored in the memo cache. If it is, the program will print the stored information.

Finally, the if the program can t find the number in the memo cache, it will calculate the Fibonacci numbers up to the position you ve input and store them all in the memo cache while printing the number for the position you ve input.

Practical Applications of the Fibonacci Sequence

While the Fibonacci sequence might seem useless in the real world, it has several real-world applications. Most notably, the Fibonacci sequence can be used during games of chance to improve the odds of winning. The Fibonacci sequence is mostly used with roulette and other crap games.

To use the Fibonacci sequence in games of chance, you start by defining the beginning of your sequence. Let s say five dollars. If you lose, you move up the sequence and wager another five dollars. If you lose again, you wager ten dollars (five plus five). Losing your wager moves you up the sequence, and winning moves you down.

You can also use the Fibonacci sequence to very roughly convert miles to kilometers. One mile is roughly equal to 1.609 kilometers, which is very close to the Golden Ratio. Thus, you can convert miles to kilometers using the Fibonacci sequence, though you won t get an exact answer.

The Golden Ratio and the Fibonacci sequence also see use in economics, music, and optics. You can also see the Golden Ratio or Fibonacci sequence expressed in nature, such as sunflowers, leaf growth, and nautilus shells.

Popular EVs in Ohio
You can do a rough conversion from miles to kilometers using the Fibonacci sequence.

TierneyMJ/Shutterstock.com

Final Thoughts

The Fibonacci series exercise is a common coding exercise done by programmers worldwide as they learn the ins and outs of a new programming language. This is a pretty beginner programming exercise, but it s an effective and fun way to learn how to use functions in a new language. If our article helped you learn something new about programming or maths, let us know in the comments below or on social media! We love to hear from our readers.

Leave a Comment