You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CalculatePI.java 664B

1234567891011121314151617181920212223242526
  1. import java.util.Random;
  2. public class CalculatePI {
  3. static Random r = new Random();
  4. static double piApproximation = 1.0f;
  5. static int repetitions = 500000;
  6. static int iteration = 0;
  7. static double inSquare = 0;
  8. static double inCircle = 0;
  9. public static void main(String[] args) {
  10. for (iteration = 0;iteration<repetitions;iteration++) approximate();
  11. piApproximation = (inCircle/inSquare)*4.0f;
  12. System.out.println("After "+repetitions+" iterations, pi is estimated to be "+piApproximation);
  13. }
  14. public static void approximate() {
  15. double x = r.nextDouble();
  16. double y = r.nextDouble();
  17. inSquare++;
  18. if (x*x + y*y < 1) {inCircle++;}
  19. }
  20. }