Mathematical Operations Write an application that invokes a function to calculat
ID: 3759192 • Letter: M
Question
Mathematical Operations Write an application that invokes a function to calculate a binomial distribution: where The function declaration should look like binomial(p,n,k) Write three different versions of this function: (1) use the already-defined recursive factorial( ) function, and use for( ) loops for the calculation of pk and (1 p)nk , (2) use factorial( ) function and a recursive function for calculating pk and (1 p)nk , (3) a complete recursive function for everything. In the last “complete” version, use the following fact: Note that both the numerator and the denominator have k terms. Write an application that invokes a function to calculate a Poisson probability distribution: where a = np. The function declaration should look like poisson(p,n,k) Show that Poisson probability is close to that of the binomial probability for large (>10) values of n.
Explanation / Answer
import java.util.Random;
public class Util{
// calculate the binomial distribution
// ret[0] stores the number user given
// ret[1] stores the count of the corresponding number in ret[0] with the
// same index
// for some number, the count maybe 0.
// the parameter validation must be finished in advance
public static long[][] getBinomialDistribution(int min, int max, long total) {
Random rand = new Random(System.currentTimeMillis());
int n = max - min;
long[][] ret = new long[2][n + 1];
int mean = (n + 1) / 2;
float p = 1;
if (n > 0) {
p = (float) mean / (float) n;
}
long count = 0;
for (int i = 0; i <= n; i++) {
double p_i = combination(n, i) * Math.pow(p, i)
* Math.pow((1 - p), (n - i));
long count_i = (long) (total * p_i);
ret[0][i] = i + min;
ret[1][i] = count_i;
count += count_i;
}
while (count < total) {
int i = rand.nextInt(n + 1);
ret[1][i]++;
count++;
}
return ret;
}
// calculate the combination
// the value would be very large, so store it in the type of double
public static double combination(int n, int k) {
double ret = 1;
while (k > 0) {
ret = ret * ((double) n / (double) k);
k--;
n--;
}
return ret;
}
}