76

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

Mike Vella
  • 10,187
  • 14
  • 59
  • 86

5 Answers5

141
import random

def decision(probability):
    return random.random() < probability
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 5
    Note that `random.random()` generates numbers uniformally in [0, 1). 0 inclusive and 1 exclusive – one Jan 15 '21 at 08:51
3

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).

Jan Rüegg
  • 9,587
  • 8
  • 63
  • 105
Blindy
  • 65,249
  • 10
  • 91
  • 131
  • 16
    This question is tagged `python`, so your code sample seems a little out of place. – Daenyth May 04 '11 at 17:06
  • 1
    @Blindy +1 Thanks for the Pseudo Code ;) I am from a Java background and quite glad I found your snippet - even if the question is tagged Python. – AgentKnopf May 01 '12 at 11:28
  • @Zainodis, heh yea, I find C-like languages to be an almost universal language if used from a really high level! – Blindy May 01 '12 at 14:52
1

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]
OmerFI
  • 106
  • 1
  • 1
  • 7
0

I use this to generate a random boolean in python with a probability:

from random import randint
n=8 # inverse of probability
rand_bool=randint(0,n*n-1)%n==0

so to expand that :

def rand_bool(prob):
    s=str(prob)
    p=s.index('.')
    d=10**(len(s)-p)
    return randint(0,d*d-1)%d<int(s[p+1:])

I came up with this myself but it seems to work.

aritra
  • 1
  • 1
-2

If you want to amass a lot of data, I would suggest using a map:

    from numpy import random as rn
    p = 0.15
    data = rn.random(100)
    final_data = list(map(lambda x: x < p, data))
shahaf
  • 4,750
  • 2
  • 29
  • 32
Paul
  • 9