Stetus

ProbabilityCalculator

Sep 19th, 2013
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. import java.lang.Math;
  2.  
  3.  
  4. public class ProbabilityCalculator {
  5.    
  6.     //calculate probability without replacement with two quantities and n of the first quantity
  7.     private float probabilityWithoutReplacement(int k1, int k2, int n){
  8.         float probability = 1;
  9.        
  10.         while(n > 0){
  11.             probability *= (float) k1/(k1+k2);
  12.             n--;
  13.             k1--;
  14.         }
  15.        
  16.         return probability;
  17.     }
  18.    
  19.    
  20.     //calculate the probability of exactly k successes in n trials given probability p
  21.     private float binomialProbability(int n, float p, int k){
  22.         float probability = 0;
  23.         probability = binomialCoefficient(n,k)* ((float) Math.pow(((double) p),
  24.                 ((double) k))) * ((float) Math.pow((double)(1-p), ((double)(n-k)) ));
  25.         return probability;
  26.     }
  27.    
  28.     /*
  29.      * Calculate the binomial coefficient using the formula n!/(k!(n-k)!)
  30.      */
  31.     private float binomialCoefficient(int n, int k){
  32.         float coefficient = 0;
  33.         coefficient = (float) factorial(n)/(factorial(k)*factorial(n-k));
  34.         return coefficient;    
  35.     }
  36.    
  37.     //Calculate the factorial of an integer
  38.     private int factorial(int factor){
  39.         int product = 1;
  40.         while(factor > 0){
  41.             product *= factor;
  42.             factor--;
  43.         }
  44.         return product;
  45.     }
  46.  
  47.    
  48.     //Only for testing purposes. Prints the probability of getting 5 successes
  49.     //when drawing 5 times replacing and constant probability of .5
  50.     public static void main(String[] args){
  51.         ProbabilityCalculator pc = new ProbabilityCalculator();
  52.         System.out.printf("Med tilbakelegging: P= %.02f%%%n", (pc.binomialProbability(2,
  53.                 pc.probabilityWithoutReplacement(4, 6, 1), 2) * 100)); //6 sorte, 4 hvite
  54.         System.out.printf("Uten tilbakelegging: P= %.02f%%%n", (pc.probabilityWithoutReplacement(6, 4, 2)) * 100);
  55.  
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment