In Python, you can generate a random number following a Gaussian (normal) distribution using several built-in functions. The most common and straightforward ways are from the random and numpy libraries.
random moduleimport random
# mean = 0, standard deviation = 1
x = random.gauss(mu=0, sigma=1)
print(x)
Explanation:
mu: mean (center of the distribution)sigma: standard deviation (spread)random.normalvariate()import random
x = random.normalvariate(mu=10, sigma=2)
print(x)
This does the same as random.gauss(), but uses a slightly different internal algorithm. Both are valid for most use cases.
import numpy as np
# One sample
x = np.random.normal(loc=0, scale=1)
print(x)
# Multiple samples
samples = np.random.normal(loc=0, scale=1, size=1000)
print(samples[:10]) # first 10 samples
Explanation:
loc: meanscale: standard deviationsize: number of samplesIf you need more control or want to work with distributions formally:
from scipy.stats import norm
# mean = 0, std = 1
x = norm.rvs(loc=0, scale=1)
print(x)
You can also use methods like pdf(), cdf(), etc., for probability calculations.
In summary:
random.gauss().numpy.random.normal().scipy.stats.norm.