/** * This program calculates pi using the monte carlo method * * Mark Monarch * 2/26/15 */ import java.util.Scanner; public class piCalculator { public static void main() { // set up input Scanner in = new Scanner(System.in); // declare variables long trials, inCircle = 0; double x, y, piEstimate = 0; // asks user for number of trials. The more trials the more accurate System.out.print("Input number of trials: "); trials = in.nextLong(); // run trials for (int i = 0; i < trials; i++) { System.out.println("step " + (i+1) + " of " + trials ); for (int j = 0; j < 100000000; j++) { x = Math.random(); y = Math.random(); if (x*x+y*y <= 1) { inCircle++; } } piEstimate += 4.0 * (float) inCircle / 100000000.0; inCircle = 0; } // Calculate pi piEstimate /= trials; // print results System.out.println("Pi is approximately: " + piEstimate); } }