Monte Carlo simulation models probability and examines the outcomes of systems with "many coupled degrees of freedom", according to Wikipedia. From my latest blog post, a double pendulum would be another example of how this simulation technique can be applied. Aside from physical applications, the Monte Carlo simulation is also popularly incorporated in risk analysis and modeling phenomena with huge uncertainty.
Below is a probabilistic interpretation of pi. The simulation generates random x and y coordinates and plots them in the plane. Using the circle's equation, the program then detects whether the coordinates fall within the circle of radius 200 pixels. Finally, it takes the ratio of the coordinates in the circle to the total coordinates and displays the value. As the number of dots increases, the accuracy, as you can see, also increases. The idea is to generate random values within certain boundaries and feed these random values into a system and analyze trends of the outputs. Credits to this.
See the Pen NWbwjvB by steven oh (@stevenohohohohoh) on CodePen.
import java.util.ArrayList; import java.util.Random; public class Main { public static void main(String[] args) { ArrayListestamatedPi = new ArrayList<>(); int insideCircle = 0; int totalCircle = 0; for(int i = 0; i < 10000000; i++){ int x = getRandomFromRange(1, 400); int y = getRandomFromRange(1, 400); int dSquared = (int) (Math.pow((x - 200), 2) + Math.pow((y - 200), 2)); if (dSquared < 40000) { insideCircle++; } totalCircle++; estamatedPi.add(4 * (float)(insideCircle) /(float)(totalCircle)); } System.out.println(estamatedPi.get(estamatedPi.size()-1)); } private static int getRandomFromRange(int min, int max){ Random rand = new Random(); return rand.nextInt(max - min + 1) + min; } }
I looped this 10000000 times and graphed the ratio of circles landed in circles to total circles.
This graph is also a direct visual representation of the law of big numbers (yea the name is quite meh). The law of big numbers claims that as the number of trials increases, the observed results approach the theoretical or expected value. Within the law of big numbers, there are the strong law of big numbers and weak law of big numbers. This approximation of pi would be classified as an example of the strong law of big numbers, as the experimental value "almost surely converges" to an expected value. On the other side, the weak law of big numbers represents that the observed, or experimental variable falls within a probabilistic interval. But, don't all approximations such as this one count as weak law of big numbers? I don't know.