Skip to content

azeemmirza/middle-square

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Middle Square

A simple implementation of the Middle Square pseudo-random number generator in Python.

The Middle Square Method

The Middle Square Method is a simple pseudo-random number generator (PRNG) introduced by John von Neumann in 1949. The algorithm works as follows:

  1. Start with an initial seed (an integer of n digits).
  2. Square the seed to obtain a number with up to 2n digits.
  3. If necessary, pad the result with leading zeros to ensure it has 2n digits.
  4. Extract the middle n digits of the squared number; this becomes the next number in the sequence and the new seed.
  5. Repeat the process to generate further numbers.

While the method is easy to implement, it is not suitable for cryptographic or high-quality random number generation, as the sequence can quickly degenerate into short cycles or zero. However, it remains a classic example in the study of PRNGs and is useful for educational purposes.

Usage

from middle_square.core import MiddleSquare
ms = MiddleSquare(seed=1234, digit=4)
print(ms.next())  # Generate next number
ms.reset(5678)    # Reset with a new seed

Running Tests

From the project root, run:

python -m unittest discover tests

Or directly:

python tests/test.py

License

MIT License

Author: Azeem Mirza

About

The middle-square method is a method of generating pseudo random numbers.

Topics

Resources

License

Stars

Watchers

Forks

Contributors

Languages