Random boolean

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

What I have:

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? It seems inefficient and cumbersome. I don't need this to be perfect, as it is just used to simulate data, but I need it to be as fast as possible.

I searched (Google / SO) and did not find any other questions for this.

+4
source share
3 answers

Just return the test:

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

because the result of the operator < below the operator is already logical. You also do not need to specify an initial value.

Note that you need to use less than if you would like True return for a given percentage; if percent = 100 , then you want True all the time, for example. when all the values ​​obtained by randrange() are below the percent value.

+15
source

What about:

 def reset(percent=50): return random.randrange(0, 100) > percent 
+1
source

@rjbez You requested a function that returns true in X percent of the 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 correct relationship

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

All Articles