本文介绍了随机布尔值(按百分比)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一个随机布尔值,但具有加权百分比.例如,我希望用户输入一个百分比(即60),然后生成器将随机选择60%的时间.

I'm trying to get a get a random boolean but with a weighted percentage. For instance, I want the user to pass in a percentage (i.e. 60) and the generator will randomly select true 60% of the time.

我有什么?

def reset(percent=50):
    prob = random.randrange(0,100)
    if prob > percent:
        return True
    else:
        return False

是否有更好的方法可以做到这一点?这似乎效率低下且麻烦.我不需要它是完美的,因为它仅用于模拟数据,但是我需要它尽可能快.

Is there a better way to do this? This seems inefficient and cumbersome. I don't need it to be perfect since it is just used to simulate data, but I need this to be as fast as possible.

我已经搜索过(Google/SO),但没有发现其他任何问题.

I've searched (Google/SO) and have not found any other questions for this.

推荐答案

只需返回测试:

def reset(percent=50):
    return random.randrange(100) < percent

因为小于运算符的<的结果已经是布尔值.您也无需提供起始值.

because the result of a < lower than operator is already a boolean. You do not need to give a starting value either.

请注意,如果要以给定百分比返回True,则需要使用低于 的值;如果percent = 100,则您始终需要True,例如当randrange()产生的所有值都低于percent值时.

Note that you need to use lower than if you want True to be returned for a given percentage; if percent = 100 then you want True all of the time, e.g. when all values that randrange() produces are below the percent value.

这篇关于随机布尔值(按百分比)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:04