Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private void calculatePi()
- {
- Random rand = new Random();
- int alreadyReduced = 0;
- // reuse totalLoops instead of magic numbers throughout the code
- final int totalLoops = 5000;
- for (int i = 0; i < totalLoops; ++i)
- {
- // ensure the randomly generated number is greater than 0
- int numerator = Math.abs(rand.nextInt()) + 1;
- int denominator = Math.abs(rand.nextInt()) + 1;
- Ratio ratio = new Ratio(numerator, denominator);
- if (numerator == ratio.getNumerator() && denominator == ratio.getDenominator())
- {
- alreadyReduced++;
- }
- }
- double probability = ((double) alreadyReduced / (double) totalLoops);
- double pi = Math.sqrt(6.0 / probability);
- /*
- * html tags are used to force word wrapping
- * use String.format to limit the representation of pi to 3 decimal places
- */
- myLabel.setText(String.format("<html>\u03C0 is approximately %.3f</html>", pi));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement