@@ -0,0 +1,2046 @@
+import java.util.Random;%0A%0A/**%0A * Created by kenny on 5/29/14.%0A */%0Apublic class MonteCarloEvaluatePi %7B%0A%0A    private static final Random RANDOM = new Random();%0A    /*%0A        A_circle = %CF%80r%5E2%0A        A_square = (2r)%5E2%0A%0A        circle transcribed in a square, r_c = r_s = r%0A%0A        A_square / A_circle (r = 1) = ratio of areas between square and circle%0A        = 4 / %CF%80%0A      */%0A    public static void main(String%5B%5D args) %7B%0A        monteCarlo(10);%0A        monteCarlo(100);%0A        monteCarlo(1000);%0A        monteCarlo(10000);%0A        monteCarlo(100000);%0A        monteCarlo(1000000);%0A        monteCarlo(10000000);%0A        monteCarlo(100000000);%0A    %7D%0A%0A    /*%0A        make n random guesses, take the ratio of guesses in the circle,%0A        and divide that by the total guesses (all of which will be in the square)%0A        this will give you the A_square / A_circle ratio, 4/%CF%80%0A    */%0A    public static void monteCarlo(final int randomSamples) %7B%0A        int inCircle = 0;%0A        for(int i = 0; i %3C randomSamples; i++) %7B%0A            // generate random x/y variables between -1, 1 (which are guaranteed to be within the square%0A            final double x = 2 * RANDOM.nextDouble() - 1;%0A            final double y = 2 * RANDOM.nextDouble() - 1;%0A            if(inCircle(x, y)) %7B%0A                inCircle++;%0A            %7D%0A        %7D%0A        final double ratio = (double) inCircle / randomSamples;%0A        final double piApprox = ratio * 4; // ratio is 4/%CF%80, so multiply by 4 to get %CF%80 approximation%0A%0A        System.out.println(%22Random Samples: %22 + randomSamples);%0A        System.out.println(%22In circle: %22 + inCircle + %22, In square: %22 + randomSamples);%0A        System.out.println(%22PI Approximation: %22 + piApprox + %22, Error: %22 + Math.abs(Math.PI - piApprox));%0A    %7D%0A%0A    /*%0A        eq of circle centered at origin: x%5E2 + y%5E2 = r%5E2%0A        if (x)%5E2 + (y)%5E2 %3C r%5E2 then is within circle where r = 1%0A     */%0A    private static boolean inCircle(final double x, final double y) %7B%0A        // System.out.println(x + %22, %22 + y);%0A        return x * x + y * y %3C 1.0;%0A    %7D%0A%0A%7D%0A

add monte-carlo java demo