Genere un número binario aleatorio con una proporción variable de '1' bits

Necesito una función para generar enteros aleatorios. (asume Javalong Escriba por ahora, pero esto se extenderá aBigInteger oBitSet luego.)

La parte difícil es que hay un parámetro P que especifica la probabilidad (independiente) de que cualquier bit en el resultado sea 1.

Si P = 0.5 entonces solo podemos usar el generador de números aleatorios estándar. Algunos otros valores de P también son fáciles de implementar. Aquí hay un ejemplo incompleto:

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);
    }
}

¿Hay una manera de generalizar esto para cualquier valor de P entre 0.0 y 1.0?

Respuestas a la pregunta(7)

Su respuesta a la pregunta