/* * Java program to compute the value of pi using Monte Carlo * * command-line arguments: number_of_samples, seed */ package csci3366.hw2; import java.util.Random; public class MonteCarloPi { /* main method */ public static void main(String[] args) { String usageMsg = "arguments are number_of_samples seed"; /* process command-line arguments */ if (args.length != 2) { System.err.println(usageMsg); System.exit(1); } int numSamples = 0; int seed = 0; try { numSamples = Integer.parseInt(args[0]); seed = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.err.println(usageMsg); System.exit(1); } /* record start time */ long startTime = System.currentTimeMillis(); /* do calculation */ Random randGenerator = new Random(seed); int count = 0; for (int i = 0; i < numSamples; ++i) { double x = randGenerator.nextDouble(); double y = randGenerator.nextDouble(); if ((x*x + y*y) <= 1.0) ++count; } double pi = 4.0 * (double) count / (double) numSamples; /* record end time and print results */ long endTime = System.currentTimeMillis(); System.out.printf("sequential Java program results:\n"); System.out.printf("number of samples = %d, seed = %d\n", numSamples, seed); System.out.printf("estimated pi = %12.10f\n", pi); System.out.printf( "difference between estimated pi and math.h M_PI = %12.10f\n", Math.abs(pi - Math.PI)); System.out.printf("time to compute = %g seconds\n", ((double) (endTime - startTime) / 1000.0)); } }