python-scipyHow can I use Python Scipy to generate a Bernoulli distribution?
Using the Python Scipy library, you can generate a Bernoulli distribution by using the scipy.stats.bernoulli
function. This function takes two parameters, the probability of success and size. The probability of success is the probability of a trial resulting in a success, and size is the number of trials.
import scipy.stats as stats
# Generate a Bernoulli distribution with p=0.3
bernoulli_dist = stats.bernoulli(0.3, size=100)
# Print the first 10 values of the distribution
print(bernoulli_dist.rvs(10))
# Output
array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
The code above will generate a Bernoulli distribution with a probability of success p=0.3
and a size of 100
trials. The stats.bernoulli
function will return a frozen Bernoulli distribution object, which can then be used to generate random numbers with the rvs
method. In this example, the rvs
method is used to print the first 10 values of the distribution.
The parts of the code are as follows:
import scipy.stats as stats
imports the Scipy stats module.stats.bernoulli(0.3, size=100)
creates a Bernoulli distribution with a probability of successp=0.3
and a size of100
trials.bernoulli_dist.rvs(10)
generates 10 random numbers from the Bernoulli distribution.
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How do I use the NumPy transpose function in Python?
- How do I use Python Scipy to perform a Z test?
- How can I use Python Scipy to solve a Poisson equation?
- How to use Python, XML-RPC, and NumPy together?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How can I use Python Scipy to zoom in on an image?
- How can I use Python and Numpy to parse XML data?
- How can I use Python and SciPy to implement an ARIMA model?
See more codes...