Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

True or false output based on a probability

Is there a standard function for Python which outputs True or False probabilistically based on the input of a random number from 0 to 1?

example of what I mean:

def decision(probability):
    ...code goes here...
    return ...True or False...

the above example if given an input of, say, 0.7 will return True with a 70% probability and false with a 30% probability

like image 832
Mike Vella Avatar asked May 04 '11 16:05

Mike Vella


3 Answers

import random

def decision(probability):
    return random.random() < probability
like image 152
NPE Avatar answered Nov 18 '22 07:11

NPE


Given a function rand that returns a number between 0 and 1, you can define decision like this:

bool decision(float probability)
{
   return rand()<probability;
}

Assuming that rand() returns a value in the range [0.0, 1.0) (so can output a 0.0, will never output a 1.0).

like image 36
Blindy Avatar answered Nov 18 '22 06:11

Blindy


Just use PyProbs library. It is very easy to use.

>>> from pyprobs import Probability as pr
>>> 
>>> # You can pass float (i.e. 0.5, 0.157), int (i.e. 1, 0) or str (i.e. '50%', '3/11')
>>> pr.prob(50/100)
False
>>> pr.prob(50/100, num=5)
[False, False, False, True, False]
like image 1
OmerFI Avatar answered Nov 18 '22 07:11

OmerFI