title: Hypergeometric Distribution not working well java
body: <p>Im tring to calculate a probabilty using a Hypergeometric Distribution i got some help on this in the math.stackexchange but i am having problems calculating this in java</p>
  
  <p>Im not an expert on this, i been tring to figure it out with no luck, i know the problem is on my java code because when i try the formula on my calculator i get the right result whitch is 0.364 in this case </p>
  
  <p>This is the formula</p>
  
  <p><a href="https://i.stack.imgur.com/GDNuT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GDNuT.jpg" alt="enter image description here"></a></p>
  
  <p>The Binomial is calculated this way</p>
  
  <p><code>(K k) =   K! / ((K - k)! * k!)</code></p>
  
  <p>This is how im trying to replicate this in java code</p>
  
  <pre><code> public static void main(String[] args){
      BigDecimal[] prob = HyperGeometricDistribution(20,2,50,5);
      String _prob = prob[0] + "." +  prob[1];
      System.out.println(_prob);
  }
  
  private static BigDecimal fact(BigDecimal n) {
      BigDecimal result = BigDecimal.ONE;
      while (!n.equals(BigDecimal.ZERO)) {
          result = result.multiply(n);
          n = n.subtract(BigDecimal.ONE);
      }
      return result;
  }
  
  private static BigDecimal Binomial(int a, int b) {
      return fact(BigDecimal.valueOf(a)).divide(fact(BigDecimal.valueOf(a-b)).multiply(fact(BigDecimal.valueOf(b))), BigDecimal.ROUND_DOWN);
  }
  
  // K : Number of Successes in Population
  // k : number of Successes in Sample
  // N : Population Size
  // m : Sample Size
  private static BigDecimal[] HyperGeometricDistribution(int K,int k, int N, int m){
      return (Binomial(K,k).multiply(Binomial(N-K,m-k))).divideAndRemainder(Binomial(N,m));
  }
  </code></pre>
  
  <p>This will print 0.77 however the correct answer is 0.364 <a href="https://www.geneprof.org/GeneProf/tools/hypergeometric.jsp" rel="nofollow noreferrer">Online Example</a></p>
  
  <p>I will be using this in android, the max value i will pass in <strong>N</strong> is 3910 i need to use BigDecimals since i need to calculate 3910! and this is a huge number.</p>
  
  <p>Any help is appreciated</p>