.gamma()
Published May 26, 2025
Contribute to Docs
The .gamma()
function of the NumPy Random module generates random samples from a Gamma distribution, a two-parameter continuous probability distribution commonly used in statistics for modeling positive-valued data. The two parameters are shape
and scale
.
Syntax
numpy.random.gamma(shape, scale=1.0, size=None)
Parameters:
shape
(float or array_like of floats): The shape parameter, denoted as $\kappa$ (or $k$). Must be non-negative. Determines the shape of the distribution.scale
(float or array_like of floats, optional): The scale parameter, denoted as $\theta$. Must be non-negative. Default is1.0
. It stretches or compresses the distribution.size
(int or tuple of ints, optional): The output shape. Specifies the number or shape of random samples to generate. IfNone
(default), a single sample is returned.
Return value:
out
(ndarray or scalar): Random samples from the Gamma distribution.- If
size
isNone
, returns a singlefloat
. - If
size
is specified, returns a NumPy array of shapesize
containing the sampled values.
- If
Statistical Properties
Mean: $μ=αθμ=αθ$
Variance: $σ2=αθ2σ2=αθ2$
The probability density formula for the Gamma distribution is:
$$ p(x) = x^{k-1} \frac{e^{-x/\theta}} {\theta^{k}\Gamma(k)’} $$
- $\kappa$ is the shape, $\theta$ is scale, and $\Gamma$ is the Gamma function.
Example
This example generates two reproducible random samples from a Gamma distribution of shape = 2
and scale = 2
:
import numpy as npnp.random.seed(15)result = np.random.gamma(shape=2,scale=2,size=2)print(result)
The output for this code will be:
[2.59018924 4.28834638]
Here:
np.random.seed(15)
ensures the output is reproducible across runs.np.random.gamma()
draws two samples from the specified Gamma distribution.
Codebyte Example
This codebyte example generates a 2×3 array of Gamma-distributed random numbers with shape = 5
and scale = 1.5
:
np.random.seed(42)
sets the random seed for consistent results.size=(2, 3)
creates a 2D array with 2 rows and 3 columns of gamma-distributed samples.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours