Python NumPy: Rayleigh Distribution Explained

Last updated 3 weeks, 4 days ago | 96 views 75     5

Tags:- Python NumPy

The Rayleigh Distribution is a continuous probability distribution used to model the magnitude of a two-dimensional vector whose components are independent and normally distributed. It often appears in fields like signal processing, physics, and engineering.

With NumPy, you can easily simulate and analyze Rayleigh-distributed data.


What is the Rayleigh Distribution?

The Rayleigh distribution is a special case of the Weibull distribution and is commonly used to describe:

  • Wind speed models

  • Random signal amplitudes (e.g., radio signals)

  • Scattering noise in radar systems

Probability Density Function (PDF)

f(x;σ)=xσ2e−x22σ2,x≥0f(x; \sigma) = \frac{x}{\sigma^2} e^{-\frac{x^2}{2\sigma^2}}, \quad x \geq 0

Where:

  • xx: Random variable (≥ 0)

  • σ\sigma: Scale parameter (controls spread)


Key Statistics

Metric Formula
Mean σπ/2\sigma \sqrt{\pi / 2}
Variance (2−π/2)σ2(2 - \pi/2)\sigma^2
Mode σ\sigma
Skewness ~0.63
Kurtosis ~0.245

NumPy’s rayleigh() Function

numpy.random.Generator.rayleigh(scale=1.0, size=None)

Parameters

Parameter Description
scale Scale parameter σ\sigma
size Shape of the output array (e.g. 1000)

✅ Returns

An array of random values from a Rayleigh distribution.


✅ Example: Generate Rayleigh Data

import numpy as np

rng = np.random.default_rng(seed=42)

# Generate 1000 Rayleigh-distributed samples with scale σ = 2
data = rng.rayleigh(scale=2.0, size=1000)

print(data[:5])  # First 5 values

Visualizing the Rayleigh Distribution

import matplotlib.pyplot as plt
import seaborn as sns

sns.histplot(data, bins=30, kde=True, color='teal')
plt.title("Rayleigh Distribution (scale=2.0)")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.grid(True)
plt.show()

You’ll see a skewed distribution that peaks and tapers off.


Effect of Scale (σ)

Try generating data with different scale parameters:

scales = [0.5, 1.0, 2.0, 4.0]

for scale in scales:
    data = rng.rayleigh(scale=scale, size=1000)
    sns.kdeplot(data, label=f'scale={scale}')

plt.title("Rayleigh Distributions for Different Scales")
plt.xlabel("Value")
plt.ylabel("Density")
plt.legend()
plt.grid(True)
plt.show()

Observation:

  • A larger σ stretches the curve wider (more spread).

  • A smaller σ compresses it, making the peak sharper.


Real-Life Applications

Field Use Case
Wireless Communications Signal strength variations (multipath fading)
Oceanography Wave heights in shallow water
Radar Systems Signal envelope modeling
Reliability Engineering Failure time modeling under certain conditions

Full Simulation Example: Signal Strengths

scale = 3.0  # Assume average signal strength follows Rayleigh(σ=3)
samples = rng.rayleigh(scale=scale, size=10000)

# Calculate mean and variance
print("Empirical Mean:", np.mean(samples))
print("Theoretical Mean:", scale * np.sqrt(np.pi / 2))

print("Empirical Variance:", np.var(samples))
print("Theoretical Variance:", (2 - np.pi/2) * scale**2)

# Plot histogram
sns.histplot(samples, bins=50, kde=True, color='orchid')
plt.title("Rayleigh Signal Strength Simulation (scale=3.0)")
plt.xlabel("Signal Strength")
plt.ylabel("Density")
plt.grid(True)
plt.show()

Tips for Using Rayleigh Distribution

Tip Benefit
✅ Set a seed with default_rng() Ensures reproducibility
✅ Use large samples Helps approximate theoretical values
✅ Visualize with kde=True See the smooth curve of the distribution
✅ Compare to normal/Gaussian Understand how magnitudes behave

⚠️ Common Pitfalls

Pitfall Explanation
❌ Using negative values Rayleigh distribution only supports x≥0x \geq 0
❌ Confusing with normal Rayleigh is derived from normal components, but not symmetric
❌ Wrong scale interpretation scale is not the mean; mean is σπ/2\sigma \sqrt{\pi / 2}
❌ Using numpy.random.rayleigh() Deprecated in favor of default_rng().rayleigh()

Relationship with Other Distributions

Distribution Relationship
Normal Rayleigh is the magnitude of 2D vector with normal components
Weibull Rayleigh is a Weibull with shape parameter k=2k = 2
Chi Rayleigh is a Chi distribution with 2 degrees of freedom
Exponential Rayleigh is related to the square root of exponential in some cases

Conclusion

The Rayleigh Distribution is a powerful and practical model for signal strengths, wave magnitudes, and radar systems. With NumPy, generating and analyzing Rayleigh data is simple, efficient, and effective for simulations and applied statistics.


Summary Table

Feature Value
Function rng.rayleigh(scale, size)
Support x≥0x \geq 0
Mean σπ/2\sigma \sqrt{\pi / 2}
Variance (2−π/2)σ2(2 - \pi/2)\sigma^2
Use Cases Signal processing, oceanography
Related Distributions Normal, Weibull, Chi