Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / algorithm

Numerical Sequences Generator

5.00/5 (3 votes)
26 Oct 2018CPOL2 min read 10.3K   105  
Generic algorithm to generate mathematical sequences

Introduction

A numerical sequence is a set of ordered values of a function whose domain consists of the set of all natural numbers in ascending order of the numbers. The elements of a sequence are called the terms. The n-th term of a sequence is called the general term or variable of the sequence. (*)

In other words, a sequence can be considered a list of numbers arranged in a specific order. The study of sequences and their properties are very useful in various branches of science.

Background

In this work, we are particularly interested in the sequences for which it is possible to calculate its elements individually through a formula parameterized by its indices.

For example, be the sequence of the triangular numbers with their first 5 numbers:

Image 1

Sequence: 1, 3, 6, 10, 15
Index:    1, 2, 3,  4,  5

Each number of this sequence can be obtained by the following formula: (i*(i+1))/2, where i is the index of the element.

Let's code!

Using the Code

The program below works as follows. 
Enter the number of terms you want and the system will generate the following numeric sequences:

  • Fibonacci, Lucas, Catalan, Cullen and Woodall numbers
  • Triangular, square, pentagonal, hexagonal sequences of numbers
  • Pronic numbers

A more detailed description of each of these sequences and your formation laws can be found at the following address: List of OEIS sequences

Python
# Numerical Sequences Generator
# Generates several mathematical sequences by calculating their terms individually
# Language: Python

# 2018, Jose Cintra
# josecintra@josecintra.com

# initialization
import math 
formulas = {'Fibonacci numbers': ['round((pow((1+math.sqrt(5))/2,i)-
                         pow((1-math.sqrt(5))/2,i))/ math.sqrt(5))',1],
            'Lucas numbers':['((1 + math.sqrt(5))/2) ** i + ((1 - math.sqrt(5))/2) ** i',0],
            'Triangular numbers': ['(i*(i+1))/2',1],
            'Square numbers': ['i*i',1],
            'Pentagonal numbers': ['(i*(3*i-1))/2',1],
            'Hexagonal numbers': ['i*(2*i-1)',1],
            'Catalan numbers': ['math.factorial(2*i)/(math.factorial(i+1)*math.factorial(i))',0],
            'Cullen numbers': ['i*2**i + 1',0],
            'Pronic numbers': ['i*(i+1)',0],
            'Woodall numbers': ['i*2**i-1',1]
           }

# Data entry
print("Mathematical sequences generator\n")
n = int(input("Enter the number of terms in the sequence: "))

# shows the sequences
for key,value in formulas.items():
  print()
  print (key)
  start = value[1]
  for i in range(0, (n + start)):
    item = int(eval(value[0]))
    if (i < start) :
      continue
    print(item,'  ', end = '')
  print()
        
# end

Points of Interest

  1. The formulas for calculating the sequence items are stored in a dictionary-like data structure with the following arrangement:
    • Key: The sequence's name
    • Value: The formula for generating the elements according to the index and a second parameter indicating the initial index of the sequence

    In the case of Triangular Numbers, the values are:

    • key: 'Triangular numbers'
    • Value: '(i*(i+1))/2',1
  2. Element calculations are done through the eval Python function. This function evaluates a string containing a piece of code and returns the result. A more detailed description of the eval function can be found at the following address: The Python Guru
     
  3. The start variable controls by which index the sequence should begin.
     
  4. Particular care must be taken with formulas that tend to generate very large values, as they can cause overflow errors or, worse, generate incorrect values. See the formula of Catalan numbers, for example. The factorial function tends to grow very rapidly.

References

Conclusion

With this structure and using the eval function, it is easy to add new sequences. Just define the formula and configure it in the dictionary. Visit github for more algorithms.

Thanks for reading!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)