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?
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?
You could use random.random
:
import random
if random.random() < percentage_chance:
print('aaa')
import random
if random.randint(0,100) < 36:
do_stuff()
randrange
function. –
Eliseo randrange
would change the behaviour. –
Carrack Just to make it more explicitly clear and more readable:
def probably(chance):
return random.random() < chance
if probably(35 / 100):
do_the_thing()
This code returns a 1, 36% of the time
import random
import math
chance = 0.36
math.floor( random.uniform(0, 1/(1-chance)) )
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
© 2022 - 2025 — McMap. All rights reserved.