'random boolean by percentage
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.
Solution 1:[1]
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.
Solution 2:[2]
How about:
def reset(percent=50):
return random.randrange(0, 100) > percent
Solution 3:[3]
@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
Solution 4:[4]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | ecatmur |
| Solution 3 | |
| Solution 4 | OmerFI |
