Generating first ten numbers of Pell series in Python
In this tutorial, you will learn about Pell Series and how to generate them in Python.
Let’s get started!
What are Pell series?
Pell Series is a series where subsequent numbers are the sum of twice the previous number and the number previous to the previous number.
It starts from 1 and 2.
Pell Series: 1,2,5,12,29,70,169,…
Look at the sequence of numbers given above and let us try to relate them to the definition of Pell Series:-
- 1 + 2*2 = 5
- 2 + 5*2 = 12
- 5 + 12 *2 = 29
- 12 + 29*2 = 70
- 29 + 70*2 = 169
and so on…
Now that you have a clear idea of what the Pell Series are, let’s move on to how we shall write the Python code to generate the same.
Code and Output
Code in Python:-
a = 1 b = 2 c = 0 print(a) print(b) for i in range(10): c = a + 2*b a = b b = c print(c)
1 2 5 12 29 70 169 408 985 2378 5741 13860
Please try to dry run the code by hand and understand how the procedure works before moving on to the solution given below!
Explanation of the Python Code
- The first number of the series needs to be initialised (a = 1).
- The second number of the series needs to be initialised (b = 2).
- Initialise the variable where we shall generate the series (c = 0).
- Now, print the first two numbers of the series and we shall print the other generated numbers consequently.
- Initiate a for loop to print multiple numbers of the Pell series. We shall be printing 10 numbers in this Python tutorial!
- Add twice the previous number and the number previous to the previous number (c = a + 2*b).
- Swap the previous number to the number previous to the previous number (a = b).
- Swap the generated number to the previous number (b = c).
- Print the generated number.