🎲 Park-Miller Random Number Generator

A Multi-Language Implementation Tutorial for Computer Science Students

By Andrew J. Pounds, Ph.D.

Departments of Chemistry and Computer Science
Mercer University

📐 The Algorithm

This tutorial implements the Park-Miller "Minimal Standard" pseudo-random number generator, a widely-used linear congruential generator (LCG) published in 1988.

seedn+1 = (a × seedn) mod m

where: a = 16807, m = 231 - 1 = 2147483647

The algorithm produces uniformly distributed pseudo-random numbers in the range (0, 1) by dividing the seed by m. It has a period of 231 - 2, making it suitable for many applications.

📚 Reference

Park, S.K. and Miller, K.W. (1988). "Random Number Generators: Good Ones Are Hard to Find." Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201.

Implementation & Tutorial: Andrew J. Pounds, Ph.D.
Departments of Chemistry and Computer Science, Mercer University

F90

Fortran 90 Implementation

Compile with GNU Fortran (gfortran)

Fortran remains a powerhouse for scientific computing. This implementation uses real(kind=8) for double-precision floating-point arithmetic.

random_module.f90
! =============================================================================
! Park-Miller Minimal Standard Random Number Generator
! 
! Adapted from: Park, S.K. & Miller, K.W. (1988)
! "Random Number Generators: Good Ones Are Hard to Find"
! Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201
!
! Implementation by Andrew J. Pounds, Ph.D.
! Departments of Chemistry and Computer Science
! Mercer University
! =============================================================================

module random_module
    implicit none
    contains

    real(kind=8) function random(seed)
        ! Generate a pseudo-random number in the range (0, 1)
        ! The seed is modified in place for subsequent calls
        
        real(kind=8), intent(inout) :: seed
        real(kind=8) :: a, m, temp
        
        a = 16807.0D0
        m = 2147483647.0D0
        
        temp = a * seed
        seed = temp - m * int(temp / m)
        random = seed / m
        
    end function random

end module random_module
random_demo.f90
! =============================================================================
! Demonstration Program for Park-Miller Random Number Generator
!
! Andrew J. Pounds, Ph.D.
! Departments of Chemistry and Computer Science
! Mercer University
! =============================================================================

program random_demo
    use random_module
    implicit none
    
    real(kind=8) :: seed
    real(kind=8) :: r
    integer :: i
    
    ! Initialize the seed (must be a positive integer)
    seed = 12345.0D0
    
    print '(A)', '========================================'
    print '(A)', '  Park-Miller Random Number Generator'
    print '(A)', '        Fortran 90 Implementation'
    print '(A)', '========================================'
    print '(A, F12.1)', 'Initial seed: ', seed
    print '(A)', ''
    print '(A)', 'Generating 10 random numbers:'
    print '(A)', '----------------------------------------'
    
    do i = 1, 10
        r = random(seed)
        print '(A, I2, A, F12.10)', '  Random #', i, ': ', r
    end do
    
    print '(A)', '----------------------------------------'
    print '(A, F15.1)', 'Final seed value: ', seed
    
end program random_demo

🛠️ Compilation & Execution Instructions

  1. Save both files in the same directory
  2. Open a terminal and navigate to that directory
  3. Compile with: gfortran -o random_demo random_module.f90 random_demo.f90
  4. Run with: ./random_demo (Linux/Mac) or random_demo.exe (Windows)
Sample Output:
========================================
  Park-Miller Random Number Generator
        Fortran 90 Implementation
========================================
Initial seed:      12345.0

Generating 10 random numbers:
----------------------------------------
  Random # 1: 0.0966224549
  Random # 2: 0.8337370640
  Random # 3: 0.2155289068
  Random # 4: 0.1277814767
  Random # 5: 0.8585279845
  Random # 6: 0.3814536885
  Random # 7: 0.5765169992
  Random # 8: 0.9277756208
  Random # 9: 0.5765213017
  Random #10: 0.8975644596
----------------------------------------
Final seed value:    1928327257.0
λ

Common Lisp Implementation

Run with Steel Bank Common Lisp (SBCL)

Lisp's functional paradigm offers an elegant approach. We use a closure to maintain the seed state, providing a clean interface for generating random numbers.

random-generator.lisp
;;;; =============================================================================
;;;; Park-Miller Minimal Standard Random Number Generator
;;;; Common Lisp Implementation for SBCL
;;;;
;;;; Adapted from: Park, S.K. & Miller, K.W. (1988)
;;;; "Random Number Generators: Good Ones Are Hard to Find"
;;;; Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201
;;;;
;;;; Implementation by Andrew J. Pounds, Ph.D.
;;;; Departments of Chemistry and Computer Science
;;;; Mercer University
;;;; =============================================================================

(defconstant +a+ 16807.0d0
  "Multiplier constant for Park-Miller algorithm")

(defconstant +m+ 2147483647.0d0
  "Modulus constant (2^31 - 1)")

(defun make-random-generator (initial-seed)
  "Create a random number generator with the given initial seed.
   Returns a closure that generates random numbers in (0, 1)."
  (let ((seed (coerce initial-seed 'double-float)))
    (lambda ()
      (let ((temp (* +a+ seed)))
        (setf seed (- temp (* +m+ (floor temp +m+))))
        (/ seed +m+)))))

(defun park-miller-random (seed)
  "Direct implementation returning both the random value and new seed.
   Returns (values random-number new-seed)"
  (let* ((seed-float (coerce seed 'double-float))
         (temp (* +a+ seed-float))
         (new-seed (- temp (* +m+ (floor temp +m+)))))
    (values (/ new-seed +m+) new-seed)))

;;;; Demonstration Program

(defun main ()
  "Main demonstration function"
  (format t "~%========================================")
  (format t "~%  Park-Miller Random Number Generator")
  (format t "~%      Common Lisp Implementation")
  (format t "~%========================================~%")
  
  ;; Method 1: Using a closure (recommended)
  (format t "~%Method 1: Using closure~%")
  (format t "Initial seed: 12345~%")
  (format t "----------------------------------------~%")
  
  (let ((rng (make-random-generator 12345)))
    (dotimes (i 10)
      (format t "  Random #~2D: ~12,10F~%" (1+ i) (funcall rng))))
  
  ;; Method 2: Using multiple values
  (format t "~%Method 2: Explicit seed threading~%")
  (format t "----------------------------------------~%")
  
  (let ((seed 12345.0d0))
    (dotimes (i 5)
      (multiple-value-bind (r new-seed) (park-miller-random seed)
        (format t "  Random #~2D: ~12,10F  (seed: ~A)~%" 
                (1+ i) r (floor new-seed))
        (setf seed new-seed))))
  
  (format t "----------------------------------------~%"))

;; Run if executed as script
(main)

🛠️ Execution Instructions

  1. Save the file as random-generator.lisp
  2. Make sure SBCL is installed: sudo apt install sbcl (Debian/Ubuntu)
  3. Run with: sbcl --script random-generator.lisp
  4. Or interactively: sbcl --load random-generator.lisp
Sample Output:
========================================
  Park-Miller Random Number Generator
      Common Lisp Implementation
========================================

Method 1: Using closure
Initial seed: 12345
----------------------------------------
  Random # 1: 0.0966224549
  Random # 2: 0.8337370640
  Random # 3: 0.2155289068
  Random # 4: 0.1277814767
  Random # 5: 0.8585279845
  Random # 6: 0.3814536885
  Random # 7: 0.5765169992
  Random # 8: 0.9277756208
  Random # 9: 0.5765213017
  Random #10: 0.8975644596

Method 2: Explicit seed threading
----------------------------------------
  Random # 1: 0.0966224549  (seed: 207482415)
  Random # 2: 0.8337370640  (seed: 1790989824)
  Random # 3: 0.2155289068  (seed: 463031754)
  Random # 4: 0.1277814767  (seed: 274504103)
  Random # 5: 0.8585279845  (seed: 1844477029)
----------------------------------------
P

Pascal Implementation

Compile with Free Pascal Compiler (fpc)

Pascal's clear syntax makes this algorithm easy to understand. This implementation follows the original paper's Pascal pseudocode closely, using Double for precision.

random_demo.pas
{******************************************************************************
 * Park-Miller Minimal Standard Random Number Generator
 * Pascal Implementation for Free Pascal Compiler
 *
 * Adapted from: Park, S.K. & Miller, K.W. (1988)
 * "Random Number Generators: Good Ones Are Hard to Find"
 * Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201
 *
 * Implementation by Andrew J. Pounds, Ph.D.
 * Departments of Chemistry and Computer Science
 * Mercer University
 ******************************************************************************}

program RandomDemo;

const
    A: Double = 16807.0;
    M: Double = 2147483647.0;

var
    Seed: Double;

{ Generate a pseudo-random number in the range (0, 1) }
function ParkMillerRandom: Double;
var
    Temp: Double;
begin
    Temp := A * Seed;
    Seed := Temp - M * Trunc(Temp / M);
    ParkMillerRandom := Seed / M;
end;

{ Alternative version with explicit seed parameter }
function RandomWithSeed(var S: Double): Double;
var
    Temp: Double;
begin
    Temp := A * S;
    S := Temp - M * Trunc(Temp / M);
    RandomWithSeed := S / M;
end;

{ Main Program }
var
    I: Integer;
    R: Double;
    AltSeed: Double;
    
begin
    WriteLn('========================================');
    WriteLn('  Park-Miller Random Number Generator');
    WriteLn('       Pascal Implementation');
    WriteLn('========================================');
    
    { Initialize seed }
    Seed := 12345.0;
    
    WriteLn;
    WriteLn('Initial seed: ', Seed:10:1);
    WriteLn;
    WriteLn('Generating 10 random numbers:');
    WriteLn('----------------------------------------');
    
    for I := 1 to 10 do
    begin
        R := ParkMillerRandom;
        WriteLn('  Random #', I:2, ': ', R:12:10);
    end;
    
    WriteLn('----------------------------------------');
    WriteLn('Final seed value: ', Seed:15:1);
    
    { Demonstrate alternate function }
    WriteLn;
    WriteLn('Using explicit seed parameter:');
    WriteLn('----------------------------------------');
    AltSeed := 99999.0;
    for I := 1 to 3 do
    begin
        R := RandomWithSeed(AltSeed);
        WriteLn('  Random #', I:2, ': ', R:12:10);
    end;
    WriteLn('----------------------------------------');
end.

🛠️ Compilation & Execution Instructions

  1. Save the file as random_demo.pas
  2. Install Free Pascal: sudo apt install fpc (Debian/Ubuntu)
  3. Compile with: fpc random_demo.pas
  4. Run with: ./random_demo (Linux/Mac) or random_demo.exe (Windows)
Sample Output:
========================================
  Park-Miller Random Number Generator
       Pascal Implementation
========================================

Initial seed:    12345.0

Generating 10 random numbers:
----------------------------------------
  Random # 1: 0.0966224549
  Random # 2: 0.8337370640
  Random # 3: 0.2155289068
  Random # 4: 0.1277814767
  Random # 5: 0.8585279845
  Random # 6: 0.3814536885
  Random # 7: 0.5765169992
  Random # 8: 0.9277756208
  Random # 9: 0.5765213017
  Random #10: 0.8975644596
----------------------------------------
Final seed value:     1928327257.0

Using explicit seed parameter:
----------------------------------------
  Random # 1: 0.7817742836
  Random # 2: 0.3339596808
  Random # 3: 0.9141920102
----------------------------------------
Ada

Ada Implementation

Compile with GNAT (GNU Ada compiler)

Ada's strong typing and safety features make it ideal for reliable scientific computing. This implementation uses a package structure, demonstrating Ada's modular design.

park_miller.ads
-------------------------------------------------------------------------------
-- Park-Miller Minimal Standard Random Number Generator
-- Ada Package Specification
--
-- Adapted from: Park, S.K. & Miller, K.W. (1988)
-- "Random Number Generators: Good Ones Are Hard to Find"
-- Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201
--
-- Implementation by Andrew J. Pounds, Ph.D.
-- Departments of Chemistry and Computer Science
-- Mercer University
-------------------------------------------------------------------------------

package Park_Miller is

   -- Type for the random number generator state
   type Generator is private;
   
   -- Initialize generator with a seed value
   procedure Initialize (Gen : out Generator; Seed : in Long_Float);
   
   -- Generate next random number in range (0, 1)
   function Random (Gen : in out Generator) return Long_Float;
   
   -- Get current seed value
   function Get_Seed (Gen : in Generator) return Long_Float;

private

   type Generator is record
      Seed : Long_Float := 1.0;
   end record;

end Park_Miller;
park_miller.adb
-------------------------------------------------------------------------------
-- Park-Miller Minimal Standard Random Number Generator
-- Ada Package Body
--
-- Implementation by Andrew J. Pounds, Ph.D.
-- Departments of Chemistry and Computer Science
-- Mercer University
-------------------------------------------------------------------------------

package body Park_Miller is

   -- Algorithm constants
   A : constant Long_Float := 16807.0;
   M : constant Long_Float := 2147483647.0;

   procedure Initialize (Gen : out Generator; Seed : in Long_Float) is
   begin
      Gen.Seed := Seed;
   end Initialize;

   function Random (Gen : in out Generator) return Long_Float is
      Temp : Long_Float;
   begin
      Temp := A * Gen.Seed;
      Gen.Seed := Temp - M * Long_Float'Truncation (Temp / M);
      return Gen.Seed / M;
   end Random;

   function Get_Seed (Gen : in Generator) return Long_Float is
   begin
      return Gen.Seed;
   end Get_Seed;

end Park_Miller;
random_demo.adb
-------------------------------------------------------------------------------
-- Demonstration Program for Park-Miller Random Number Generator
--
-- Andrew J. Pounds, Ph.D.
-- Departments of Chemistry and Computer Science
-- Mercer University
-------------------------------------------------------------------------------

with Ada.Text_IO;           use Ada.Text_IO;
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
with Ada.Integer_Text_IO;   use Ada.Integer_Text_IO;
with Park_Miller;           use Park_Miller;

procedure Random_Demo is
   Gen : Generator;
   R   : Long_Float;
begin
   Put_Line ("========================================");
   Put_Line ("  Park-Miller Random Number Generator");
   Put_Line ("          Ada Implementation");
   Put_Line ("========================================");
   New_Line;
   
   -- Initialize the generator
   Initialize (Gen, 12345.0);
   
   Put ("Initial seed: ");
   Put (Get_Seed (Gen), Fore => 10, Aft => 1, Exp => 0);
   New_Line (2);
   
   Put_Line ("Generating 10 random numbers:");
   Put_Line ("----------------------------------------");
   
   for I in 1 .. 10 loop
      R := Random (Gen);
      Put ("  Random #");
      Put (I, Width => 2);
      Put (": ");
      Put (R, Fore => 1, Aft => 10, Exp => 0);
      New_Line;
   end loop;
   
   Put_Line ("----------------------------------------");
   Put ("Final seed value: ");
   Put (Get_Seed (Gen), Fore => 12, Aft => 1, Exp => 0);
   New_Line;
   
end Random_Demo;

🛠️ Compilation & Execution Instructions

  1. Save all three files in the same directory
  2. Install GNAT: sudo apt install gnat (Debian/Ubuntu)
  3. Compile with: gnatmake random_demo.adb
  4. Run with: ./random_demo (Linux/Mac) or random_demo.exe (Windows)
Sample Output:
========================================
  Park-Miller Random Number Generator
          Ada Implementation
========================================

Initial seed:    12345.0

Generating 10 random numbers:
----------------------------------------
  Random # 1: 0.0966224549
  Random # 2: 0.8337370640
  Random # 3: 0.2155289068
  Random # 4: 0.1277814767
  Random # 5: 0.8585279845
  Random # 6: 0.3814536885
  Random # 7: 0.5765169992
  Random # 8: 0.9277756208
  Random # 9: 0.5765213017
  Random #10: 0.8975644596
----------------------------------------
Final seed value:    1928327257.0
🦀

Rust Implementation

Compile with rustc or build with Cargo

Rust's ownership system ensures memory safety while maintaining performance. This implementation demonstrates both a struct-based approach and a simple function.

park_miller.rs
//! =============================================================================
//! Park-Miller Minimal Standard Random Number Generator
//! Rust Implementation
//!
//! Adapted from: Park, S.K. & Miller, K.W. (1988)
//! "Random Number Generators: Good Ones Are Hard to Find"
//! Communications of the ACM, Vol. 31, No. 10, pp. 1192-1201
//!
//! Implementation by Andrew J. Pounds, Ph.D.
//! Departments of Chemistry and Computer Science
//! Mercer University
//! =============================================================================

/// Constants for the Park-Miller algorithm
const A: f64 = 16807.0;
const M: f64 = 2147483647.0;

/// A Park-Miller random number generator
pub struct ParkMillerRng {
    seed: f64,
}

impl ParkMillerRng {
    /// Create a new generator with the given seed
    pub fn new(seed: f64) -> Self {
        ParkMillerRng { seed }
    }

    /// Generate the next random number in the range (0, 1)
    pub fn next(&mut self) -> f64 {
        let temp = A * self.seed;
        self.seed = temp - M * (temp / M).trunc();
        self.seed / M
    }

    /// Get the current seed value
    pub fn get_seed(&self) -> f64 {
        self.seed
    }
}

/// Functional approach: returns (random_value, new_seed)
pub fn park_miller_random(seed: f64) -> (f64, f64) {
    let temp = A * seed;
    let new_seed = temp - M * (temp / M).trunc();
    (new_seed / M, new_seed)
}

/// Iterator implementation for easy use with Rust's iterator patterns
impl Iterator for ParkMillerRng {
    type Item = f64;

    fn next(&mut self) -> Option<Self::Item> {
        Some(Self::next(self))
    }
}

fn main() {
    println!("========================================");
    println!("  Park-Miller Random Number Generator");
    println!("         Rust Implementation");
    println!("========================================");
    println!();

    // Method 1: Using the struct
    println!("Method 1: Using ParkMillerRng struct");
    println!("Initial seed: 12345");
    println!("----------------------------------------");

    let mut rng = ParkMillerRng::new(12345.0);
    
    for i in 1..=10 {
        let r = rng.next();
        println!("  Random #{:2}: {:.10}", i, r);
    }

    println!("----------------------------------------");
    println!("Final seed value: {:.1}", rng.get_seed());
    println!();

    // Method 2: Using iterator pattern
    println!("Method 2: Using iterator (first 5 values)");
    println!("----------------------------------------");

    let rng2 = ParkMillerRng::new(12345.0);
    for (i, r) in rng2.take(5).enumerate() {
        println!("  Random #{:2}: {:.10}", i + 1, r);
    }
    println!("----------------------------------------");
    println!();

    // Method 3: Functional approach
    println!("Method 3: Functional approach");
    println!("----------------------------------------");

    let mut seed = 12345.0;
    for i in 1..=3 {
        let (r, new_seed) = park_miller_random(seed);
        println!("  Random #{}: {:.10}  (seed: {:.0})", i, r, new_seed);
        seed = new_seed;
    }
    println!("----------------------------------------");
}

🛠️ Compilation & Execution Instructions

Option A: Using rustc directly

  1. Save the file as park_miller.rs
  2. Compile with: rustc park_miller.rs -o park_miller
  3. Run with: ./park_miller (Linux/Mac) or park_miller.exe (Windows)

Option B: Using Cargo (recommended)

  1. Create project: cargo new park_miller && cd park_miller
  2. Replace src/main.rs with the code above
  3. Build and run: cargo run --release
Sample Output:
========================================
  Park-Miller Random Number Generator
         Rust Implementation
========================================

Method 1: Using ParkMillerRng struct
Initial seed: 12345
----------------------------------------
  Random # 1: 0.0966224549
  Random # 2: 0.8337370640
  Random # 3: 0.2155289068
  Random # 4: 0.1277814767
  Random # 5: 0.8585279845
  Random # 6: 0.3814536885
  Random # 7: 0.5765169992
  Random # 8: 0.9277756208
  Random # 9: 0.5765213017
  Random #10: 0.8975644596
----------------------------------------
Final seed value: 1928327257.0

Method 2: Using iterator (first 5 values)
----------------------------------------
  Random # 1: 0.0966224549
  Random # 2: 0.8337370640
  Random # 3: 0.2155289068
  Random # 4: 0.1277814767
  Random # 5: 0.8585279845
----------------------------------------

Method 3: Functional approach
----------------------------------------
  Random #1: 0.0966224549  (seed: 207482415)
  Random #2: 0.8337370640  (seed: 1790989824)
  Random #3: 0.2155289068  (seed: 463031754)
----------------------------------------