True or false output based on a probability
Asked Answered
I

6

79

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

Informal answered 4/5, 2011 at 16:52 Comment(0)
F
145
import random

def decision(probability):
    return random.random() < probability
Faria answered 4/5, 2011 at 16:56 Comment(1)
Note that random.random() generates numbers uniformally in [0, 1). 0 inclusive and 1 exclusiveLucubrate
C
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).

Caridadcarie answered 4/5, 2011 at 16:56 Comment(3)
This question is tagged python, so your code sample seems a little out of place.Entreaty
@Caridadcarie +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.Burn
@Zainodis, heh yea, I find C-like languages to be an almost universal language if used from a really high level!Caridadcarie
H
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]
Haw answered 24/8, 2021 at 8:34 Comment(0)
H
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.

Hominid answered 31/5, 2020 at 13:15 Comment(0)
D
0
import numpy as np
def prob(p):    # takes a probability in %
    a = np.random.randint(1,101) 
    if a <= p:             
        decision = True
    else: decision = False
    return decision

Simple function for a boolean return value based on a input probability.

Deadbeat answered 23/1 at 13:53 Comment(1)
Looks like you are not quite answering the question that the OP is asking. The OP is asking for a probability of each answer, not true or false as the return.Cowfish
T
-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))
Tillio answered 28/10, 2019 at 13:54 Comment(1)
What does this add that any of the answers of 8 years don't?Washin

© 2022 - 2024 — McMap. All rights reserved.