/****************************************************************************** * Compute π using the Monte Carlo method. * * Copyright © 2017 Richard Lesh. All rights reserved. *****************************************************************************/ import org.pureprogrammer.Utils; public class ComputePi2 { static final int MAX_SAMPLES = 1000000; public static void main(String[] args) { int insideCount = 0; for (int i = 0; i < MAX_SAMPLES; ++i) { final double x = Math.random(); final double y = Math.random(); if (x * x + y * y <= 1.0) { ++insideCount; } } final double pi = ((double)(insideCount) / (double)(MAX_SAMPLES)) * 4; System.out.println(Utils.format("pi: {0:.15f}", pi)); System.out.println(Utils.format("abs(pi - π): {0:.10e}", Math.abs(pi - Math.PI))); } }