random.gauss / normalvariate
Both give the same distribution with different algorithms, so the same seed gives different numbers. gauss() computes two values at a time and hands out the second on the next call; sigma is the standard deviation, not the variance.
Demo
import random random.seed(42) [round(random.gauss(0.0, 1.0), 4) for _ in range(5)]
gauss() uses Box-Muller: two uniform floats give two normal values, cos(...) * r is returned and sin(...) * r is stored for the next call. That is why getstate()[2] after one call with seed 42 holds -0.172904: the second value of the gauss tab (shown there as -0.1729). normalvariate() (Kinderman-Monahan) draws pairs of uniforms in a loop and keeps nothing. The values are rounded because they come from the C math library, which can differ in the last digit between platforms.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| mu | float | no (0.0) | The mean (center of the bell curve). Default since 3.11. |
| sigma | float | no (1.0) | The standard deviation (width). Default since 3.11. 0 returns mu every time. |
Return value
float — mu + z * sigma for a standard normal z; any real value is possible.
Common patterns
import random readings = [true_value + random.gauss(0, 0.5) for _ in range(100)]
import random duration = max(0.0, random.gauss(15.0, 3.5))
import random import threading local = threading.local() def rng(): if not hasattr(local, "r"): local.r = random.Random() return local.r
Examples
Pitfalls
import random import statistics random.seed(42) data = [random.gauss(0, 4) for _ in range(10000)] round(statistics.stdev(data))
import random import statistics random.seed(42) data = [random.gauss(0, 2) for _ in range(10000)] round(statistics.stdev(data))
import random random.seed(42) min(random.gauss(1, 2) for _ in range(1000)) < 0
import random random.seed(42) min(max(0.0, random.gauss(1, 2)) for _ in range(1000))
When to use
- Noise, measurement error, natural variation around a mean
- Monte Carlo simulations needing normal inputs
- normalvariate when several threads share one generator
- Bounded values → triangular, betavariate or clamping
- Positive skewed quantities (incomes, durations) → lognormvariate, gammavariate
- Arrays of millions of values → numpy.random.Generator.normal
Notes
FAQ
Same normal distribution, different algorithms. gauss() (Box-Muller) produces two values per computation and caches one, so it is slightly faster but not safe for simultaneous calls from two threads; normalvariate() keeps no cache. For the same seed they return different numbers.