Advertisement
bojjenclon

Ratio

Sep 7th, 2014
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1. private void calculatePi()
  2. {
  3.     Random rand = new Random();
  4.    
  5.     int alreadyReduced = 0;
  6.     // reuse totalLoops instead of magic numbers throughout the code
  7.     final int totalLoops = 5000;
  8.     for (int i = 0; i < totalLoops; ++i)
  9.     {
  10.         // ensure the randomly generated number is greater than 0
  11.         int numerator = Math.abs(rand.nextInt()) + 1;
  12.         int denominator = Math.abs(rand.nextInt()) + 1;
  13.        
  14.         Ratio ratio = new Ratio(numerator, denominator);
  15.        
  16.         if (numerator == ratio.getNumerator() && denominator == ratio.getDenominator())
  17.         {
  18.             alreadyReduced++;
  19.         }
  20.     }
  21.    
  22.     double probability = ((double) alreadyReduced / (double) totalLoops);
  23.     double pi = Math.sqrt(6.0 / probability);
  24.    
  25.     /*
  26.      *  html tags are used to force word wrapping
  27.      *  use String.format to limit the representation of pi to 3 decimal places
  28.      */
  29.     myLabel.setText(String.format("<html>\u03C0 is approximately %.3f</html>", pi));
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement