Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python random.binomialvariate() Method



Therandom.binomialvariate() method in Python used to generates a random number that follows a binomial distribution. This method returns the number of successes in n independent trials, given that each trial has a probability p of success.

The equivalent mathematical expression of this random.binomialvariate() method is as follows −

sum(random() < p for i in range(n))

The number of trials n must be a non-negative integer, and p must be a probability value between 0 and 1 (inclusive). These ensure that the generated random variable conforms to the properties of a binomial distribution and the resultant integer must be in the range 0 <= X <= n.

This method was introduced in Python version 3.12. If your Python version is earlier than 3.12, and you are attempting to use this method, it will raise an AttributeError: module 'random' has no attribute 'binomialvariate'.

Syntax

Following is the syntax of therandom.binomialvariate() method −

random.binomialvariate(n=1, p=0.5)

Parameters

This method accepts the following parameter −

  • n: This parameter represents the number of independent trials or experiments. It must be a non-negative integer.

  • p: This is the probability of success on each trial. It must be a value between 0.0 and 1.0, inclusive.

Return Value

This method returns an integer that represents the number of successes in the n trials.

Example 1

Following is a basic example of therandom.binomialvariate() method −

import random# number of trialsn = 10  # probability of success in each trialp = 0.5  # Generate a random value following a binomial distributionnumber_of_successes = random.binomialvariate(n, p)print("Number of successes: ",number_of_successes)

Following is the output −

Number of successes:  4

Note: The Output generated will be different for every execution as it returns a random item.

Example 2

Following is an example to generate the random numbers from a binomial distribution.

import randomATOMS = 1000000DECAY_PROB = 0.1for i in range(10):    print(random.binomialvariate(ATOMS, DECAY_PROB))

While executing the above code you will get the similar output like below −

9942499757997911002139997099557100113100077100354100256
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp