Random Example — uniform, normal, and gamma distributions

This example calls utilities.random_generate() to draw 1 000 samples from three distributions — Uniform(0, 1), Normal(0, 1), and Gamma(2, 2) — then prints a summary statistics table and plots the histograms.

Example Code

"""IMSL random number generation example: uniform, normal, and gamma.

Outputs:
- Table of statistics printed to stdout
- SVG histogram saved to test_output/demo_imsl_random.svg
"""
from __future__ import annotations

from pathlib import Path
from typing import Dict

import matplotlib.pyplot as plt
import numpy as np

from utilities import random_generate


def run_demo_imsl_random() -> Dict[str, object]:
    """Generate and analyse 1000 random samples from three distributions.

    Args:
        None

    Returns:
        Dict[str, object]: Result dict with arrays ``uniform``, ``normal``,
            ``gamma`` (each of length 1000) and ``plot_path`` (str).
    """
    n = 1000
    uniform = random_generate(n, "uniform", seed=0)
    normal = random_generate(n, "normal", seed=1)
    gamma_samples = random_generate(n, "gamma", seed=2, shape=2.0, scale=2.0)

    distributions = {
        "Uniform(0,1)": uniform,
        "Normal(0,1)": normal,
        "Gamma(2,2)": gamma_samples,
    }

    print("\nIMSL Random Generation Example — n=1000 per distribution")
    print("=" * 60)
    print(f"{'Distribution':<20} {'Mean':>10} {'Std':>10} {'Min':>10} {'Max':>10}")
    print("-" * 60)
    for name, arr in distributions.items():
        print(
            f"{name:<20} {arr.mean():>10.4f} {arr.std():>10.4f}"
            f" {arr.min():>10.4f} {arr.max():>10.4f}"
        )
    print("-" * 60)

    output_dir = Path("test_output")
    output_dir.mkdir(parents=True, exist_ok=True)
    plot_path = output_dir / "demo_imsl_random.svg"

    fig, axes = plt.subplots(1, 3, figsize=(15, 5))
    colors = ["#b45309", "#d97706", "#92400e"]
    for ax, (name, arr), color in zip(axes, distributions.items(), colors):
        ax.hist(arr, bins=30, color=color, alpha=0.85, edgecolor="white", linewidth=0.5)
        ax.set_title(f"{name}\nμ={arr.mean():.3f}, σ={arr.std():.3f}")
        ax.set_xlabel("Value")
        ax.set_ylabel("Frequency")
        ax.grid(True, alpha=0.3)

    fig.suptitle("IMSL Random Generation: uniform, normal, gamma", fontweight="bold")
    fig.tight_layout()
    fig.savefig(plot_path, format="svg")
    plt.close(fig)

    print(f"\nPlot saved to: {plot_path}")
    return {
        "uniform": uniform,
        "normal": normal,
        "gamma": gamma_samples,
        "plot_path": str(plot_path),
    }


if __name__ == "__main__":
    run_demo_imsl_random()

Plot Output

Three histograms for uniform, normal, and gamma distributions

Histograms of 1 000 samples per distribution with mean and standard deviation annotated in each panel title.

Console Output

IMSL Random Generation Example ù n=1000 per distribution
============================================================
Distribution               Mean        Std        Min        Max
------------------------------------------------------------
Uniform(0,1)             0.5169     0.2846     0.0002     0.9995
Normal(0,1)             -0.0543     0.9863    -3.5488     3.7516
Gamma(2,2)               3.8347     2.7544     0.0961    19.5386
------------------------------------------------------------

Plot saved to: test_output\demo_imsl_random.svg