Skip to content

Instantly share code, notes, and snippets.

@joriki
Created June 24, 2018 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joriki/025831ea79af531e09aab6fc1cebdaf6 to your computer and use it in GitHub Desktop.
Save joriki/025831ea79af531e09aab6fc1cebdaf6 to your computer and use it in GitHub Desktop.
Calculate probabilities for the number of bits to set in a uniformly random bit string to simulate a higher density of bits; see https://math.stackexchange.com/questions/2830624
import java.math.BigInteger;
public class Question2830624 {
final static double p = 0.5;
final static double q = 0.6;
final static int n = 20;
public static void main (String [] args) {
double [] a = new double [n + 1];
double [] b = new double [n + 1];
double [] f = new double [n + 1];
for (int k = 0;k <= n;k++) {
a [k] = binomialCoefficient (n,k) * Math.pow (p,k) * Math.pow (1 - p,n - k);
b [k] = binomialCoefficient (n,k) * Math.pow (q,k) * Math.pow (1 - q,n - k);
}
for (int k = 0;k <= n;k++) {
double [] c = new double [k + 1];
for (int i = 0;i <= k;i++)
for (int j = 0;j <= i;j++)
c [i] += a [k - j] * binomialCoefficient (n - k + j,j) * binomialCoefficient (k - j,i - j) / binomialCoefficient (n,i);
f [k] = b [k];
for (int i = 0;i < k;i++)
f [k] -= c [i] * f [i];
f [k] /= c [k];
}
double sum = 0;
for (int k = 0;k <= n;k++) {
System.out.println (k + " " + f [k]);
sum += f [k];
}
System.out.println ();
System.out.println ("sum: " + sum);
}
static BigInteger factorial (long n) {
return n == 0 ? BigInteger.ONE : factorial (n - 1).multiply (BigInteger.valueOf (n));
}
static double binomialCoefficient (long n,long k) {
return factorial (n).divide (factorial (k)).divide (factorial (n - k)).doubleValue ();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment