8000 Merge pull request #25413 from linus-md/beta-2 · numpy/numpy@9fd38f9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9fd38f9

Browse files
authored
Merge pull request #25413 from linus-md/beta-2
DOC: Add example to ``rng.beta(...)``
2 parents 84595f6 + 1b35a60 commit 9fd38f9

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

numpy/random/_generator.pyx

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ cdef class Generator:
366366
Draw samples from a Beta distribution.
367367
368368
The Beta distribution is a special case of the Dirichlet distribution,
369-
and is related to the Gamma distribution. It has the probability
369+
and is related to the Gamma distribution. It has the probability
370370
distribution function
371371
372372
.. math:: f(x; a,b) = \\frac{1}{B(\\alpha, \\beta)} x^{\\alpha - 1}
@@ -396,6 +396,44 @@ cdef class Generator:
396396
out : ndarray or scalar
397397
Drawn samples from the parameterized beta distribution.
398398
399+
Examples
400+
--------
401+
The beta distribution has mean a/(a+b). If ``a == b`` and both
402+
are > 1, the distribution is symmetric with mean 0.5.
403+
404+
>>> rng = np.random.default_rng()
405+
>>> a, b, size = 2.0, 2.0, 10000
406+
>>> sample = rng.beta(a=a, b=b, size=size)
407+
>>> np.mean(sample)
408+
0.5047328775385895 # may vary
409+
410+
Otherwise the distribution is skewed left or right according to
411+
whether ``a`` or ``b`` is greater. The distribution is mirror
412+
symmetric. See for example:
413+
414+
>>> a, b, size = 2, 7, 10000
415+
>>> sample_left = rng.beta(a=a, b=b, size=size)
416+
>>> sample_right = rng.beta(a=b, b=a, size=size)
417+
>>> m_left, m_right = np.mean(sample_left), np.mean(sample_right)
418+
>>> print(m_left, m_right)
419+
0.2238596793678923 0.7774613834041182 # may vary
420+
>>> print(m_left - a/(a+b))
421+
0.001637457145670096 # may vary
422+
>>> print(m_right - b/(a+b))
423+
-0.0003163943736596009 # may vary
424+
425+
Display the histogram of the two samples:
426+
427+
>>> import matplotlib.pyplot as plt
428+
>>> plt.hist([sample_left, sample_right],
429+
... 50, density=True, histtype='bar')
430+
>>> plt.show()
431+
432+
References
433+
----------
434+
.. [1] Wikipedia, "Beta distribution",
435+
https://en.wikipedia.org/wiki/Beta_distribution
436+
399437
"""
400438
return cont(&random_beta, &self._bitgen, size, self.lock, 2,
401439
a, 'a', CONS_POSITIVE,

0 commit comments

Comments
 (0)
0