Percentage chance to make action
Asked Answered
M

5

44

Simple problem:

percentage_chance = 0.36

if some_function(percentage_chance):
   # action here has 36% chance to execute
   pass

How can I write some_function, or an expression involving percentage_chance, in order to solve this problem?

Margiemargin answered 8/7, 2010 at 11:37 Comment(0)
E
60

You could use random.random:

import random

if random.random() < percentage_chance:
    print('aaa')
Eliseo answered 8/7, 2010 at 11:40 Comment(2)
Great, now i have random.randrange(1,100) in range(1,int(chance*100)) but i don't think is this right.Margiemargin
random.random returns a floating point number, a continuous range, while randrange returns an int by default, so it's a set of discrete points within the range. If your percentage chance falls between the discrete points, it's like rounding it up or down to the nearest.Capuche
C
21
import random
if random.randint(0,100) < 36:
    do_stuff()
Chimene answered 8/7, 2010 at 11:42 Comment(2)
it is better to use randrange function.Eliseo
That comment needs qualifying randrange would change the behaviour.Carrack
B
7

Just to make it more explicitly clear and more readable:

def probably(chance):
    return random.random() < chance

if probably(35 / 100):
    do_the_thing()
Bettencourt answered 20/3, 2021 at 17:33 Comment(0)
D
1

This code returns a 1, 36% of the time

import random
import math
chance = 0.36
math.floor( random.uniform(0, 1/(1-chance)) )
Denominate answered 28/9, 2020 at 16:49 Comment(0)
R
0

Just multiply random() by 100 if you want to work with integer percentage

from random import random, randint

# return True 36% of the time
def fu(percent):
    if random()*100 < 36:
        return True
    return False

if fu(36):
    # action here has 36% chance to execute
    pass

# 36 percent indeed
n = 1000000
print(sum(True for _ in range(n) if fu(36)) / n * 100)

Don't do this (it's [1, 100] making it 101 possibilities)

if randint(0,100) < 36:
    pass

# chance here is 36/101 == 35.64356435643564
print(sum(True for _ in range(n) if randint(0,101) < 36) / n * 100)

Also note that randint is much slower than random

Robotize answered 21/5, 2024 at 15:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.