A simple implementation of the Middle Square pseudo-random number generator in Python.
The Middle Square Method is a simple pseudo-random number generator (PRNG) introduced by John von Neumann in 1949. The algorithm works as follows:
- Start with an initial seed (an integer of n digits).
- Square the seed to obtain a number with up to 2n digits.
- If necessary, pad the result with leading zeros to ensure it has 2n digits.
- Extract the middle n digits of the squared number; this becomes the next number in the sequence and the new seed.
- 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.
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 seedFrom the project root, run:
python -m unittest discover testsOr directly:
python tests/test.pyMIT License
Author: Azeem Mirza