long
类型,但稍后会扩展到BigInteger
或BitSet
)。其中棘手的部分是有一个参数P,它指定了结果中任意一位为1的概率(独立事件)。如果P = 0.5,则可以使用标准的随机数生成器。其他一些P值也很容易实现。以下是一个不完整的示例:
Random random = new Random();
// ...
long nextLong(float p) {
if (p == 0.0f) return 0L;
else if (p == 1.0f) return -1L;
else if (p == 0.5f) return random.nextLong();
else if (p == 0.25f) return nextLong(0.5f) & nextLong(0.5f);
else if (p == 0.75f) return nextLong(0.5f) | nextLong(0.5f);
else if (p == 0.375f) return nextLong(0.5f) & nextLong(0.75f); // etc
else {
// What goes here??
String message = String.format("P=%f not implemented yet!", p);
throw new IllegalArgumentException(message);
}
}
有没有一种方法可以将此推广到介于0.0和1.0之间的任何P值?