This repository contains a C++ implementation of the ran2 pseudo-random number generator, based on Chapter 7 of Numerical Recipes in C. It includes uniform distribution tests, automated visualization using gnuplot, and a Python testing suite to verify correctness.
The ran2 algorithm is a long-period (0.0 and 1.0 (exclusive of the endpoint values).
- High-Quality PRNG: Implementation of the classic
ran2algorithm. - Helper Interface:
Randomize(): Dynamically seeds the generator usingtime(NULL).Random(): Returns a uniform double in the range[0.0, 1.0).Random(int N): Returns a uniform integer in the range[0, N).
- Distribution Analysis: Automatically bins the generated sequence into 20 sub-intervals to test for uniform distribution.
- Auto-plotting: Generates a GNUplot configuration (
temp.txt) and exports a distribution plot (PRNG1.png).
To compile and run the application, you need:
- A C++ compiler (e.g.,
g++orclang++). gnuplotinstalled on your system (optional, required to generate the plot image).
- macOS (via Homebrew):
brew install gnuplot
- Ubuntu/Debian:
sudo apt-get install gnuplot
Compile the source code using the following shell command:
g++ -o PRNG.out PRNG.cpp -OfastRun the compiled binary:
./PRNG.out- The program asks you to specify the number of random numbers to generate:
(Enter an integer, e.g.,
chand adad random mikhayd? (yek adade integer vared konid)=10000) - It prints the generated random sequence.
- It prints the frequency distribution counts (
p[i]) across 20 bins. - It prints the normalized frequencies.
- It compiles a gnuplot script (
temp.txt) and runs it to save the plot asPRNG1.png.
An automated Python test script is provided in the repository to compile, run, and validate the C++ code's functionality and statistical behavior.
To run the tests:
python3 test_prng.py- Successful compilation of
PRNG.cpp. - Boundary check of all generated random numbers (must be in
[0.0, 1.0)). - Integrity of the frequency binning (sum of bins must equal the total requested samples).
- Verification of normalized frequencies.
- Verification of output files (
temp.txtandPRNG1.png). - Statistical sanity check (the mean of the generated uniform distribution must be close to
0.5).
This implementation is based on the ran2 routine from Numerical Recipes in C. Please refer to Numerical Recipes for their licensing terms.