/* * Monte Carlo PI * * Calculation converges towards PI using a Monte Carlo simulation. * * Note: This simulation will never converge on the correct value for PI as * the displayed whitespace is only an approximation of a quarter-circle. * * More Info: http://programmingpraxis.com/2009/10/09/calculating-pi/ * * Wally Glutton 2009 * http://stungeye.com * * License: http://creativecommons.org/licenses/by-sa/3.0/ * */ final int R = 400; final color BLUE = color(0, 0, 255); final color WHITE = color(255, 255, 255); final color RED = color(255, 0, 0); final color BLACK = color(0, 0, 0); int n = 0; int count = 0; void setup () { size(R,R+45); PFont font = loadFont("CenturyGothic-Bold-12.vlw"); textFont(font); background(0); fill(255); stroke(255); ellipse(0, R, R*2, R*2); stroke(0); // Exhaustive search of all pixels shows the closest // approximation we'll ever get to PI. /* loadPixels(); for (int i = 0; i < (R*R); i++) { if (pixels[i] == WHITE) n++; } println(4 * n / (double)(R * R)); // Prints 3.147825 for R = 400 */ } void show_values() { fill(0); rect(0,R,width,45); fill(255); double pi = 4 * n / (double)count; text("Approximately PI: " + pi, 10, height - 25); text("Scatter Count: " + count, 10, height - 10); } void draw() { int random_x = (int)random(R); int random_y = (int)random(R); loadPixels(); color current_pixel_colour = pixels[random_y * R + random_x]; if (current_pixel_colour == BLACK) { set(random_x, random_y, RED); } else if (current_pixel_colour != RED) { n++; if (current_pixel_colour == WHITE) { set(random_x, random_y, BLUE); } } count++; show_values(); }