Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 577
rjbez Avatar asked Jan 14 '13 18:01

rjbez


People also ask

How do you find the random Boolean value?

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.

How do you generate a random Boolean in Python?

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.

How do you randomize true or false in C#?

If you want to create a random boolean, use this code: var random = new Random(); var randomBool = random.


2 Answers

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.

like image 68
Martijn Pieters Avatar answered Oct 26 '22 23:10

Martijn Pieters


How about:

def reset(percent=50):
    return random.randrange(0, 100) > percent
like image 40
ecatmur Avatar answered Oct 26 '22 23:10

ecatmur