random.gammavariate / betavariate
gammavariate is the gamma DISTRIBUTION, not math.gamma. Its beta is a scale (mean = alpha * beta); some textbooks use a rate instead. betavariate(alpha, beta) draws two gammas and returns y / (y + z).
Demo
import random random.seed(42) [round(random.gammavariate(2.0, 1.0), 4) for _ in range(5)]
gammavariate switches algorithm on alpha: above 1 it uses Cheng's rejection method, exactly 1 is -log(1 - random()) * beta (so alpha 1, beta 3 gives three times the expovariate(1.0) values), below 1 it uses algorithm GS with x ** (1 / alpha). betavariate(2, 5) has mean 2 / 7, so most draws are small. The values are rounded because log, exp and ** come from the platform C library.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| alpha | float | yes | Shape, > 0. For betavariate: the "successes" side. |
| beta | float | yes | gammavariate: scale (> 0, mean = alpha * beta). betavariate: second shape (> 0). |
Return value
float — gammavariate: x > 0 with mean alpha * beta. betavariate: 0 <= x <= 1 with mean alpha / (alpha + beta).
Common patterns
import random samples = {v: random.betavariate(wins[v] + 1, losses[v] + 1) for v in variants} choice = max(samples, key=samples.get)
import random x = random.gammavariate(shape, 1 / rate)
import random g = [random.gammavariate(a, 1.0) for a in (2.0, 3.0, 5.0)] shares = [x / sum(g) for x in g]
Examples
Pitfalls
import random random.seed(42) round(sum(random.gammavariate(2.0, 3.0) for _ in range(10000)) / 10000, 2)
import random random.seed(42) round(sum(random.gammavariate(2.0, 1 / 3) for _ in range(10000)) / 10000, 2)
import random random.seed(42) random.betavariate(0, 1)
import random random.seed(42) random.betavariate(2, 5) < 1
When to use
- Waiting time until the alpha-th event, positive skewed quantities: gammavariate
- Random probabilities and proportions, Bayesian priors: betavariate
- The gamma FUNCTION → math.gamma / math.lgamma
- Exponential waiting times → expovariate
- Many draws for statistics work → numpy.random.Generator.gamma / beta
Notes
FAQ
No. It draws a random number from the gamma distribution. The gamma function itself is math.gamma(x) (and math.lgamma for its logarithm).