13

I'm trying to get a get a random boolean but with a weighted percentage. For instance, I want the user to pass in a percentage (i.e. 60) and the generator will randomly select true 60% of the time.

What I have is this:

def reset(percent=50):
    prob = random.randrange(0,100)
    if prob > percent:
        return True
    else:
        return False

Is there a better way to do this? This seems inefficient and cumbersome. I don't need it to be perfect since it is just used to simulate data, but I need this to be as fast as possible.

I've searched (Google/SO) and have not found any other questions for this.

rjbez
  • 802
  • 2
  • 12
  • 21
  • Possible duplicate of [True or false output based on a probability](http://stackoverflow.com/questions/5886987/true-or-false-output-based-on-a-probability) – Martin Thoma Jan 28 '17 at 08:49

4 Answers4

26

Just return the test:

def reset(percent=50):
    return random.randrange(100) < percent

because the result of a < lower than operator is already a boolean. You do not need to give a starting value either.

Note that you need to use lower than if you want True to be returned for a given percentage; if percent = 100 then you want True all of the time, e.g. when all values that randrange() produces are below the percent value.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

How about:

def reset(percent=50):
    return random.randrange(0, 100) > percent
ecatmur
  • 152,476
  • 27
  • 293
  • 366
1

@rjbez You asked for a function which returns true in X percentage of time. When X == 0% it should always return false. When X == 100% it should always return true. The current accepted answer is now fixed and has the proper relation

def reset(percent=50):
    return random.randrange(100) < percent
Gregory
  • 1,479
  • 15
  • 22
  • Thanks, I suppose I should have added a comment about that. I did figure that out long ago and updated the code but not the question. – rjbez Oct 29 '14 at 12:59
0

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. '60%', '3/11')
>>> pr.Prob('50%')
False
>>> pr.Prob('50%', num=5)
[False, False, False, True, False]
OmerFI
  • 106
  • 1
  • 1
  • 7