Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using random, which form returns an equal 50% chance?

Tags:

python

random

I'm guessing that most built in random generators return something like this:

[0.0, 1.0)

so if I would like a 50% chance would I use something like this:

if random() < .5

or something like:

if random() <= .5

Thanks for the help.

like image 867
Nope Avatar asked Feb 26 '09 16:02

Nope


3 Answers

Why do it yourself? Python has random.choice :)

random.choice([0, 1]) will give you 0/1 with equal chances -- and it is a standard part of Python, coded up by the same people who wrote random.random (and thus know more about its semantics than anyone else)

like image 179
moshez Avatar answered Nov 16 '22 10:11

moshez


Ah, the old ".5" problem. Here's the answer:

If you're going to divide 10 things into two equal parts, you need 5 things in each part. 0 thru 4 in the first part, 5-9 in the second part. So... < .5 is correct.

like image 35
dwc Avatar answered Nov 16 '22 09:11

dwc


To a first approximation, either works.

The best way is to choose a random generator that specifically emits booleans or integers with range. Then you can nail the range exactly.

Operations like "equality" with floating point is iffy anyway.

like image 4
Jason Cohen Avatar answered Nov 16 '22 11:11

Jason Cohen