10000 DOC: Add example to ``rng.beta(...)`` by linus-md · Pull Request #25413 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

DOC: Add example to rng.beta(...) #25413

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 20, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion numpy/random/_generator.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ cdef class Generator:
Draw samples from a Beta distribution.

The Beta distribution is a special case of the Dirichlet distribution,
and is related to the Gamma distribution. It has the probability
and is related to the Gamma distribution. It has the probability
distribution function

.. math:: f(x; a,b) = \\frac{1}{B(\\alpha, \\beta)} x^{\\alpha - 1}
Expand Down Expand Up @@ -396,6 +396,41 @@ cdef class Generator:
out : ndarray or scalar
Drawn samples from the parameterized beta distribution.

Examples
--------
If ``a == b`` and both are > 1, the distribution is symmetric with
mean 0.5.

>>> rng = np.random.default_rng()
>>> a, b, size = 2.0, 2.0, 10000
>>> sample = rng.beta(a=a, b=b, size=size)
>>> np.mean(sample)
0.5047328775385895 # may vary

Otherwise the distribution is skewed left or right according to
whether ``a`` or ``b`` is greater. The distribution is mirror
symmetric. See for example:

>>> a, b, size = 2, 7, 10000
>>> sample_left = rng.beta(a=a, b=b, size=size)
>>> sample_right = rng.beta(a=b, b=a, size=size)
>>> m_left, m_right = np.mean(sample_left), np.mean(sample_right)
>>> m_left, m_right
(0.22334081861904062, 0.7749320166133927) # may vary
>>> m_left + m_right
0.9982728352324334 # may vary

Display the histogram of the two samples:
>>> import matplotlib.pyplot as plt
5A57 >>> plt.hist([sample_left, sample_right],
... 50, density=True, histtype='bar')
>>> plt.show()

References
----------
.. [1] Wikipedia, "Beta distribution",
https://en.wikipedia.org/wiki/Beta_distribution

"""
return cont(&random_beta, &self._bitgen, size, self.lock, 2,
a, 'a', CONS_POSITIVE,
Expand Down
0