Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.Math;
- public class ProbabilityCalculator {
- //calculate probability without replacement with two quantities and n of the first quantity
- private float probabilityWithoutReplacement(int k1, int k2, int n){
- float probability = 1;
- while(n > 0){
- probability *= (float) k1/(k1+k2);
- n--;
- k1--;
- }
- return probability;
- }
- //calculate the probability of exactly k successes in n trials given probability p
- private float binomialProbability(int n, float p, int k){
- float probability = 0;
- probability = binomialCoefficient(n,k)* ((float) Math.pow(((double) p),
- ((double) k))) * ((float) Math.pow((double)(1-p), ((double)(n-k)) ));
- return probability;
- }
- /*
- * Calculate the binomial coefficient using the formula n!/(k!(n-k)!)
- */
- private float binomialCoefficient(int n, int k){
- float coefficient = 0;
- coefficient = (float) factorial(n)/(factorial(k)*factorial(n-k));
- return coefficient;
- }
- //Calculate the factorial of an integer
- private int factorial(int factor){
- int product = 1;
- while(factor > 0){
- product *= factor;
- factor--;
- }
- return product;
- }
- //Only for testing purposes. Prints the probability of getting 5 successes
- //when drawing 5 times replacing and constant probability of .5
- public static void main(String[] args){
- ProbabilityCalculator pc = new ProbabilityCalculator();
- System.out.printf("Med tilbakelegging: P= %.02f%%%n", (pc.binomialProbability(2,
- pc.probabilityWithoutReplacement(4, 6, 1), 2) * 100)); //6 sorte, 4 hvite
- System.out.printf("Uten tilbakelegging: P= %.02f%%%n", (pc.probabilityWithoutReplacement(6, 4, 2)) * 100);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment