执行此操作的百分比机会是多少?

42

简单问题:

percentage_chance = 0.36

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

我该如何编写some_function,或者涉及percentage_chance的表达式来解决这个问题?

4个回答

59
你可以使用 random.random
import random

if random.random() < percentage_chance:
    print('aaa')

1
太好了,现在我有random.randrange(1,100)在range(1,int(chance*100))中,但我不认为这是正确的。 - methyl
random.random返回一个浮点数,一个连续的范围,而randrange默认返回一个整数,因此它是范围内一组离散的点。如果你的百分比机会落在这些离散点之间,就像将其四舍五入到最近的点。 - Mnebuerquo

20
import random
if random.randint(0,100) < 36:
    do_stuff()

4
最好使用 randrange 函数。 - SilentGhost
1
那个注释需要限定,randrange 会改变行为。 - Robin Andrews

7

为了更明确易懂:

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

if probably(35 / 100):
    do_the_thing()

1
这段代码返回1的概率为36%。
import random
import math
chance = 0.36
math.floor( random.uniform(0, 1/(1-chance)) )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接