具有权重或偏差的随机布尔值 [英] Random boolean with weight or bias
本文介绍了具有权重或偏差的随机布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要生成一些随机布尔值。但是我需要能够指定返回 true
的概率。结果如下:
I need to generate some random booleans. However I need to be able to specify the probability of returning true
. As a results doing:
private Random random = new Random();
random.nextBoolean();
不起作用。
一种可能解决方案是:
private Random random = new Random()
public boolean getRandomBoolean(float p){
return random.nextFloat() < p;
}
我想知道是否有更好或更自然的方法。
I was wondering if there is a better or more natural way of doing this.
编辑:
我想我在问是否有一个提供nextBoolean(浮动概率)方法的库类。
I guess I am asking whether there is a library class that provides a nextBoolean(float probability) method.
推荐答案
我想知道是否有更好或更自然的方法。
I was wondering if there is a better or more natural way of doing this.
您正在使用的方法很好。 * AFAIK,没有一种标准的Java方法会使这段代码更短。
The approach you're using already is fine.* AFAIK, there's not a standard Java method that will make this code any shorter.
*用于非加密目的。
这篇关于具有权重或偏差的随机布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文