相关疑难解决方法(0)

生成具有可变比例"1"位的随机二进制数

我需要一个函数来生成随机整数.(long现在假设Java 类型,但这将扩展到BigIntegerBitSet稍后.)

棘手的部分是有一个参数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 …
Run Code Online (Sandbox Code Playgroud)

java random optimization bit-manipulation

6
推荐指数
2
解决办法
3727
查看次数

标签 统计

bit-manipulation ×1

java ×1

optimization ×1

random ×1