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.
In order to generate Random boolean in Java, we use the nextBoolean() method of the java. util. Random class. This returns the next random boolean value from the random generator sequence.
getrandbits() function. The parameter 1 will generate either 1 or 0 Boolean values. Then bool() function is used to convert the integer value into a True or False Boolean value.
If you want to create a random boolean, use this code: var random = new Random(); var randomBool = random.
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.
How about:
def reset(percent=50):
return random.randrange(0, 100) > percent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With