Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real Python random percentage

Tags:

python

random

I don't understand this syntax i have found in the real python book and was hoping I could get some clarity.

from __future__ import division
from random import random

total_A_wins = 0
total_B_wins = 0

trials = 100000
for trial in range(0, trials):
    A_win = 0
    B_win = 0
    if random() < .87: # 1st region
        A_win += 1
    else:
        B_win += 1
    # determine overall election outcome
    if A_win > B_win:
        total_A_wins += 1
    else:
        total_B_wins += 1

print "Probability A wins:", total_A_wins/trials
print "Probability B wins:", total_B_wins/trials

So in the exercise they state that A has an 87% chance of winning. But how does random () < .87 define that A would get the 87%?

When I read it it states: if random is less than .87

This is what I was hoping to clarify because random being less than .87 doesn't make sense to me.

like image 424
sayth Avatar asked May 13 '26 03:05

sayth


1 Answers

The return value of random.random() is uniformly distributed across the range [0.0, 1.0) (so from 0.0 inclusive to 1.0 exclusive), so it has a equal chance of hitting any value in that range.

That means that 87% of the time, values below .87 are chosen.

If you were to change this to a test for random() < 1.0, that test would pass always, 100% of the time. If you would change it to random() < 0.0, it'd never pass, so 0% of the time. And since the distribution is uniform, random() < 0.5 would be True half of the time, since the other half of the time values in the range [0.5, 1.0) would be picked instead.

You could look at it as a dice roll; 100% of the time, you'll roll a value < 7 with a standard 6-sided dice. 0% of the time you'll roll a value < 1, 50% of the time you'll roll a value < 4 (1, 2 or 3), and 66.67% of the time you'd roll a value less than 5 (so 2/3rds of all your rolls). The random.random() return value just has a much larger range than just 6 distinct values.

like image 61
Martijn Pieters Avatar answered May 15 '26 15:05

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!