user
In Python, how to pick a random number with a Gaussian distribution?
alphonsio

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.


Option 1: Using the built-in random module

import 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)
  • Returns a single float sampled from a Gaussian distribution.

Option 2: Using 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.

Option 3: Using NumPy (for arrays or multiple samples)

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: mean
  • scale: standard deviation
  • size: number of samples

Option 4: Using SciPy (for advanced use cases)

If 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:

  • For simple random numbers → use random.gauss().
  • For large arrays or numerical work → use numpy.random.normal().
  • For statistical modeling → use scipy.stats.norm.