我想从3-10或4-6这样的范围中选择一个随机数。应该选择数字,这样,数字越低,选择的机会就越大。下面的代码仅以相同的概率选择每个数字。
private int bonusPoints;
private double randomBonusPoints = Math.Random() * 100;
bonusPoints = (int)randomBonusPoints;
如何从发行版(如P(3,4,5)=85%, P(6,7,8)=10%, P(9,10)=5%
)中进行选择
发布于 2015-01-28 15:10:39
下面是最简单的方法(从“理解代码”的角度来看):
int choice;
double r = Math.random();
if(r < .5){ //50% chance to choose 4
choice = 4;
}
else if(r < .9){ //40% chance to choose 5
choice = 5;
}
else{ //10% chance to choose 6
choice = 6;
}
显然,您可以根据其他数字和其他选择这些数字的机会进行调整,但这说明了基本情况。
还请注意,在googling中搜索“加权随机数生成器java”会返回大量结果,包括来自StackOverflow的一堆答案。
发布于 2015-01-28 15:57:40
在初始随机数上使用Math.pow
可以在不破坏随机数的情况下提供平滑的尺度。选择你的体重是开放的辩论,但这个结果看起来还可以。你也可以很明显地把它放大或缩小。
public long weightedRandom(long lowest, long highest, double weight) {
// Even distribution r >= 0 and < 1.
double r = Math.random();
// Add the weight while we are still between 0 and 1.
r = Math.pow(r, weight);
// Scale it - r >= 0 and <= highest - lowest.
r = r * (highest - lowest + 1);
// Translate to lowest.
r += lowest;
// Floor to long.
return (long) r;
}
private void test(double weight) {
List<Integer> results = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
results.add(0);
}
for (int i = 0; i < 1000; i++) {
int r = (int) weightedRandom(0, results.size() - 1, weight);
results.set(r, results.get(r) + 1);
}
System.out.println("Weight: " + weight + " Results: " + results);
}
public void test() {
test(1);
test(10);
test(.1);
test(2);
}
结果如下:
Weight: 1.0 Results: [119, 91, 112, 84, 96, 95, 86, 112, 93, 112]
Weight: 10.0 Results: [773, 57, 44, 37, 23, 15, 16, 9, 18, 8]
Weight: 0.1 Results: [0, 0, 0, 0, 0, 8, 14, 76, 243, 659]
Weight: 2.0 Results: [331, 119, 100, 85, 87, 71, 53, 59, 48, 47]
这在我看来是个尺度因素。
https://stackoverflow.com/questions/28195582
复制相似问题