Last modified: Dec 26, 2024 By Alexander Williams

Python Weibull Distribution with random.weibullvariate()

The Weibull distribution is a versatile probability distribution commonly used in reliability engineering and survival analysis. Python's random.weibullvariate(alpha, beta) helps generate random numbers following this distribution.

What is the Weibull Distribution?

The Weibull distribution is characterized by two parameters: alpha (scale parameter) and beta (shape parameter). It's particularly useful for modeling lifetime data and reliability analysis.

Similar to the exponential distribution, the Weibull distribution offers more flexibility in modeling various probability scenarios.

Parameters Explanation

Alpha (α): The scale parameter that stretches or shrinks the distribution. Must be positive.

Beta (β): The shape parameter that affects the shape of the distribution curve. Must be positive.

Basic Implementation


import random

# Generate a random number from Weibull distribution
result = random.weibullvariate(alpha=1.0, beta=1.5)
print(f"Random Weibull variate: {result}")

# Generate multiple values
values = [random.weibullvariate(1.0, 1.5) for _ in range(5)]
print(f"Multiple values: {values}")


Random Weibull variate: 0.8234567891234
Multiple values: [0.723, 1.245, 0.891, 1.567, 0.934]

Visualizing the Distribution

To better understand the distribution's behavior, let's create a histogram of Weibull variates using matplotlib:


import random
import matplotlib.pyplot as plt
import numpy as np

# Generate 1000 random numbers
samples = [random.weibullvariate(alpha=1.0, beta=2.0) for _ in range(1000)]

# Create histogram
plt.hist(samples, bins=50, density=True)
plt.title('Weibull Distribution (α=1.0, β=2.0)')
plt.xlabel('Value')
plt.ylabel('Density')
plt.show()

Effect of Parameters

Different combinations of alpha and beta parameters produce different distribution shapes. Like the gamma distribution, parameter selection is crucial.


import random

# Different parameter combinations
params = [
    (1.0, 0.5),  # β < 1: Decreasing hazard rate
    (1.0, 1.0),  # β = 1: Constant hazard rate
    (1.0, 3.0)   # β > 1: Increasing hazard rate
]

for alpha, beta in params:
    samples = [random.weibullvariate(alpha, beta) for _ in range(5)]
    print(f"α={alpha}, β={beta}: {samples}")

Practical Applications

The Weibull distribution is commonly used in:

  • Reliability engineering to model failure times
  • Weather forecasting for wind speed distributions
  • Material science for particle size distributions

Error Handling


import random

def safe_weibull(alpha, beta):
    try:
        return random.weibullvariate(alpha, beta)
    except ValueError as e:
        print(f"Error: {e}")
        return None

# Test with invalid parameters
print(safe_weibull(-1, 1))    # Invalid alpha
print(safe_weibull(1, -1))    # Invalid beta
print(safe_weibull(1, 0))     # Invalid beta

Statistical Analysis Example


import random
import statistics

# Generate sample data
data = [random.weibullvariate(2.0, 1.5) for _ in range(1000)]

# Calculate basic statistics
mean = statistics.mean(data)
median = statistics.median(data)
stdev = statistics.stdev(data)

print(f"Mean: {mean:.2f}")
print(f"Median: {median:.2f}")
print(f"Standard Deviation: {stdev:.2f}")

Integration with Other Distributions

The Weibull distribution can be compared with other distributions like the normal distribution for comprehensive statistical analysis.

Conclusion

random.weibullvariate() is a powerful tool for generating random numbers following the Weibull distribution. Understanding its parameters and applications is crucial for statistical modeling.

Whether you're working in reliability engineering, weather modeling, or general statistical analysis, this function provides a reliable way to generate Weibull-distributed random numbers.