(1) Write a program that generates uniform random numbers (continuous, [0,1], please do not use inbuilt function).
(2) Find various performance indicators for comparison of random number generators.
(3) Use the inbuilt random number generator/function and plot the three CDFs (Developed code in (1), (2), and theoretical CDF).
(4) Transform the random number generated in (1) and plot the CDF for the following random variables exponential, Pareto, and Gaussian distributions.
(5) Generate Gaussian and Lognormal distribution in the above fashion.
Assistant
Certainly! Let's address each of your tasks step-by-step using Python. We'll cover:
Implementing a Uniform Random Number Generator without Inbuilt Functions.
Identifying Performance Indicators for Random Number Generators.
Plotting Cumulative Distribution Functions (CDFs).
Transforming Uniform Random Numbers to Exponential, Pareto, and Gaussian Distributions.
Generating Gaussian and Lognormal Distributions Using the Above Method.
We'll use Python for implementation, utilizing libraries like matplotlib for plotting and numpy for numerical operations (except for random number generation in part 1).
Part 1: Implement a Uniform Random Number Generator Without Inbuilt Functions
One common method to generate uniform random numbers is the Linear Congruential Generator (LCG). It uses the recurrence relation:
[ X_{n+1} = (a \cdot X_n + c) \mod m ]
Where:
( m ) = modulus
( a ) = multiplier
( c ) = increment
( X_0 ) = seed
We'll normalize the output to [0,1] by dividing ( X_{n+1} ) by ( m ).
Implementation:
python
class LCG:
def __init__(self, seed=1, a=1664525, c=1013904223, m=2**32):
self.a = a
self.c = c
self.m = m
self.state = seed
def next_uniform(self):
self.state = (self.a * self.state + self.c) % self.m
return self.state / self.m
def generate_uniforms(self, n):
uniforms = []
for _ in range(n):
uniforms.append(self.next_uniform())
return uniforms
# Example usage:
if __name__ == "__main__":
lcg = LCG(seed=12345)
uniform_numbers = lcg.generate_uniforms(10)
print("Generated Uniform Numbers:", uniform_numbers)
Explanation:
Initialization (__init__): Sets up the LCG with specified parameters. The chosen parameters (a, c, m) are commonly used values.
next_uniform Method: Generates the next uniform random number in [0,1].
generate_uniforms Method: Generates n uniform random numbers by repeatedly calling next_uniform.
Note: The choice of parameters is crucial for the quality of randomness. The parameters provided are from Numerical Recipes but might not be suitable for cryptographic purposes.
Part 2: Performance Indicators for Comparing Random Number Generators
When evaluating random number generators (RNGs), several performance indicators can be considered:
Period Length: The length before the sequence repeats. A longer period is preferable.
Uniformity: The RNG should produce numbers that are uniformly distributed over the desired interval.
Independence: Sequential numbers should not exhibit any correlation.
Statistical Tests: Applying tests like the Chi-Square test, Kolmogorov-Smirnov test, Runs test, etc., to assess randomness.
Speed: The time taken to generate numbers, especially important for simulations requiring large datasets.
Reproducibility: Ability to produce the same sequence with the same seed, essential for debugging and experiments.
Detailed Discussion:
Period Length:
Importance: Ensures the RNG doesn't cycle too early, which could lead to repeating patterns.
Example: LCG with ( m = 2^{32} ) has a maximum period of ( m ).
Uniformity:
Assessment: Plot histograms and compare against the expected uniform distribution. Use statistical tests like the Kolmogorov-Smirnov test.
Visualization: Q-Q plots can also help visualize uniformity.
Independence:
Assessment: Analyze autocorrelation between sequential numbers. Ideally, there should be no significant correlation.
Tools: Autocorrelation plots or statistical measures like the autocorrelation function (ACF).
Statistical Tests:
Chi-Square Test: Compares the observed frequency of numbers in intervals against the expected frequency.
Kolmogorov-Smirnov Test: Compares the empirical CDF with the theoretical CDF.
Runs Test: Checks for the occurrence of patterns that deviate from randomness.
Speed:
Importance: Essential for applications requiring the generation of millions or billions of numbers.
Measurement: Time the generation process using functions like time.time() or timeit in Python.
Reproducibility:
Importance: Critical for experiments to ensure that results can be replicated.
Implementation: Using fixed seeds in RNGs.
Implementing Some Performance Indicators:
Let's implement a simple uniformity test (Histogram and KS-Test) and autocorrelation for our LCG.
python
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import kstest
def uniformity_test(rng, n):
samples = rng.generate_uniforms(n)
# Histogram
plt.hist(samples, bins=20, density=True, alpha=0.6, color='g', label='Generated')
# Theoretical Uniform CDF
x = np.linspace(0, 1, 100)
plt.plot(x, [1]*len(x), 'r--', label='Theoretical')
plt.title('Uniformity Test - Histogram')
plt.xlabel('Value')
plt.ylabel('Density')
plt.legend()
plt.show()
# Kolmogorov-Smirnov Test
ks_stat, p_value = kstest(samples, 'uniform')
print(f"KS Statistic: {ks_stat}, p-value: {p_value}")
def autocorrelation_test(samples, lag=1):
n = len(samples)
mean = np.mean(samples)
c0 = np.sum((samples - mean) ** 2) / n
c1 = np.sum((samples[:n - lag] - mean) * (samples[lag:] - mean)) / n
autocorr = c1 / c0
print(f"Autocorrelation (lag={lag}): {autocorr}")
# Example usage:
if __name__ == "__main__":
lcg = LCG(seed=12345)
n_samples = 10000
samples = lcg.generate_uniforms(n_samples)
uniformity_test(lcg, n_samples)
autocorrelation_test(samples, lag=1)
Explanation:
Histogram: Visualizes the distribution of generated numbers against the uniform expectation.
Kolmogorov-Smirnov Test: Statistical test to compare the sample distribution with the uniform distribution. A high p-value (> 0.05) suggests no significant difference.
Autocorrelation: Measures the correlation between sequential numbers. Values close to 0 indicate independence.
Note: For comprehensive evaluation, more statistical tests and higher lags for autocorrelation should be considered.
Part 3: Plotting CDFs Using Inbuilt RNG and Comparing with Theoretical CDF
We'll:
Use our implemented LCG and Python's inbuilt RNG.
Plot the empirical CDFs of both and compare them with the theoretical uniform CDF.
Implementation:
python
import numpy as np
import matplotlib.pyplot as plt
import random
def compute_empirical_cdf(data):
sorted_data = np.sort(data)
y = np.arange(1, len(sorted_data)+1) / len(sorted_data)
return sorted_data, y
def plot_cdfs(lcg_data, builtin_data, n):
# Compute empirical CDFs
lcg_sorted, lcg_cdf = compute_empirical_cdf(lcg_data)
builtin_sorted, builtin_cdf = compute_empirical_cdf(builtin_data)
# Theoretical CDF for Uniform [0,1]
x = np.linspace(0, 1, 1000)
theoretical_cdf = x # For uniform distribution
# Plotting
plt.figure(figsize=(10,6))
plt.plot(lcg_sorted, lcg_cdf, label='LCG Empirical CDF')
plt.plot(builtin_sorted, builtin_cdf, label='Built-in RNG Empirical CDF')
plt.plot(x, theoretical_cdf, 'k--', label='Theoretical Uniform CDF')
plt.title(f'Cumulative Distribution Functions (n={n})')
plt.xlabel('Value')
plt.ylabel('CDF')
plt.legend()
plt.grid(True)
plt.show()
# Example usage:
if __name__ == "__main__":
n = 10000
# LCG uniform numbers
lcg = LCG(seed=12345)
lcg_data = lcg.generate_uniforms(n)
# Built-in RNG uniform numbers
builtin_data = [random.uniform(0,1) for _ in range(n)]
plot_cdfs(lcg_data, builtin_data, n)
Explanation:
compute_empirical_cdf Function: Sorts the data and computes the empirical CDF.
plot_cdfs Function: Plots the empirical CDFs of both RNGs and the theoretical CDF.
Usage Example: Generates 10,000 uniform numbers using both LCG and Python's built-in RNG (random.uniform) and plots their CDFs alongside the theoretical CDF.
Expected Outcome:
Both empirical CDFs should closely follow the theoretical straight line for a uniform distribution.
Minor deviations might exist due to the finite sample size and inherent generator properties.
Part 4: Transforming Uniform Random Numbers to Other Distributions and Plotting CDFs
Using the Inverse Transform Sampling method, we can transform uniform random numbers into other distributions:
Since the Gaussian distribution's inverse CDF doesn't have a closed form, use the Box-Muller Transform or accept/reject methods. Alternatively, use the inverse of the error function.
Implementation:
We'll implement transformations and plot their empirical CDFs compared to theoretical CDFs.
python
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import expon, pareto, norm
def transform_exponential(u, lambd=1):
return -np.log(1 - u) / lambd
def transform_pareto(u, xm=1, alpha=3):
return xm / (1 - u) ** (1 / alpha)
def box_muller(u1, u2):
# Convert two uniform [0,1) to two standard normal random variables
z0 = np.sqrt(-2 * np.log(u1)) * np.cos(2 * np.pi * u2)
z1 = np.sqrt(-2 * np.log(u1)) * np.sin(2 * np.pi * u2)
return z0, z1
def transform_gaussian(rng, n):
# Requires even number of samples
u = rng.generate_uniforms(n)
u1 = u[::2]
u2 = u[1::2]
z0, z1 = box_muller(u1, u2)
return np.concatenate((z0, z1))
def plot_transformed_cdf(transformed_data, theoretical_dist, title, params=None):
sorted_data, empirical_cdf = compute_empirical_cdf(transformed_data)
# Theoretical CDF
x = np.linspace(min(sorted_data), max(sorted_data), 1000)
if theoretical_dist == 'exponential':
cdf_theoretical = expon.cdf(x, scale=1.0) # lambda =1
elif theoretical_dist == 'pareto':
alpha = params.get('alpha', 3)
xm = params.get('xm',1)
cdf_theoretical = pareto.cdf(x, b=alpha, scale=xm)
elif theoretical_dist == 'gaussian':
cdf_theoretical = norm.cdf(x)
else:
cdf_theoretical = None
# Plotting
plt.figure(figsize=(10,6))
plt.plot(sorted_data, empirical_cdf, label='Empirical CDF')
if cdf_theoretical is not None:
plt.plot(x, cdf_theoretical, 'k--', label='Theoretical CDF')
plt.title(f'CDF - {title}')
plt.xlabel('Value')
plt.ylabel('CDF')
plt.legend()
plt.grid(True)
plt.show()
# Example usage:
if __name__ == "__main__":
n = 10000
lcg = LCG(seed=12345)
# Exponential
u = lcg.generate_uniforms(n)
exp_data = transform_exponential(np.array(u), lambd=1)
plot_transformed_cdf(exp_data, 'exponential', 'Exponential Distribution (λ=1)')
# Pareto
pareto_params = {'alpha': 3, 'xm':1}
pareto_data = transform_pareto(np.array(u), xm=pareto_params['xm'], alpha=pareto_params['alpha'])
plot_transformed_cdf(pareto_data, 'pareto', 'Pareto Distribution (α=3, xm=1)', parameters=pareto_params)
# Gaussian
# Generate Gaussian data using Box-Muller
gaussian_data = transform_gaussian(lcg, n)
plot_transformed_cdf(gaussian_data, 'gaussian', 'Gaussian Distribution (μ=0, σ=1)')
Explanation:
Transformations:
Exponential: Applies the inverse CDF formula.
Pareto: Applies the inverse CDF formula with parameters ( \alpha ) and ( x_m ).
Gaussian: Uses the Box-Muller transform, which requires pairs of uniform random numbers to generate standard normal variables.
plot_transformed_cdf Function:
Plots the empirical CDF of the transformed data against the theoretical CDF of the target distribution.
Usage Example:
Generates 10,000 uniform numbers using LCG.
Transforms them into Exponential, Pareto, and Gaussian distributions.
Plots their CDFs for comparison.
Note:
For the Pareto distribution, ensure that the generated data adheres to ( x \geq x_m ).
The Box-Muller transform doubles the number of generated Gaussian variables (requires even ( n )). Adjust accordingly in production code.
Part 5: Generating Gaussian and Lognormal Distributions Using the Above Method
For the Lognormal Distribution, we can use the property that if ( Y ) is normally distributed, then ( X = e^{Y} ) is lognormally distributed.
transform_lognormal Function: Applies ( X = e^{\mu + \sigma Y} ), where ( Y ) is Gaussian.
plot_lognormal_cdf Function:
Computes and plots the empirical CDF of the lognormal data.
Compares it with the theoretical lognormal CDF using the inverse transformation.
Usage Example:
Generates Gaussian data using the LCG and Box-Muller transform.
Converts Gaussian data to Lognormal.
Plots the CDFs for both Gaussian and Lognormal distributions.
Note:
The theoretical CDF of the lognormal distribution is derived using the cumulative distribution of the underlying normal distribution.
Ensure that no data points are non-positive when taking the logarithm for CDF computation.
Complete Code Integration
For convenience, here's how you can integrate all parts into a single Python script. This script includes the LCG implementation, performance indicators, CDF plotting, and transformations to various distributions.
python
Explanation:
Integrated Functions: All functions from previous parts are included for seamless execution.
Main Execution:
Part 1: Demonstrates generating uniform numbers using LCG.
Part 2: Performs uniformity and autocorrelation tests.
Part 3: Plots CDFs comparing LCG and built-in RNG.
Part 4: Transforms uniform numbers to Exponential, Pareto, and Gaussian distributions and plots their CDFs.
Part 5: Generates and plots the Lognormal distribution.
Usage: Save this script as rng_analysis.py and run it using Python:
bash
python rng_analysis.py
Ensure you have the necessary libraries installed:
bash
pip install numpy matplotlib scipy
Additional Considerations
Quality of RNG:
The LCG, while simple, may not be suitable for all purposes due to potential correlations and limited entropy.
For higher-quality RNGs, consider algorithms like Mersenne Twister, XORShift, or cryptographically secure generators.
Advanced Testing:
Use suites like TestU01 for comprehensive RNG testing.
Implement more statistical tests to evaluate different aspects of randomness.
Performance Optimization:
For large-scale simulations, consider vectorized operations using numpy for speed.
Profile the code to identify and optimize bottlenecks.
Reproducibility:
Always set seeds when reproducibility is required.
Document RNG parameters used in analyses.
Scalability:
For generating billions of random numbers, ensure memory management is handled properly, possibly using generators or writing to disk incrementally.
Feel free to modify parameters, add more performance tests, or extend the transformations to other distributions as needed for your specific applications!