Skip to content

Instantly share code, notes, and snippets.

@huahualeetcode
Created January 10, 2019 07:46
Show Gist options
  • Save huahualeetcode/9f3ff5e675d861d35b23457f0594d488 to your computer and use it in GitHub Desktop.
Save huahualeetcode/9f3ff5e675d861d35b23457f0594d488 to your computer and use it in GitHub Desktop.
// Author: Huahua (https://www.youtube.com/user/xxfflower)
// p5 web editor: https://editor.p5js.org
var w = 400;
var h = 400;
var img;
var sampled = 0;
var valid = 0;
function setup() {
createCanvas(w, h);
img = createImage(w, h);
}
function computeIntegral(n) {
sampled += n;
var r = color(255, 0, 0);
var b = color(0, 0, 255);
for (var i = 0; i < n; ++i) {
var x = random();
var y = random();
var sx = floor(x * w);
var sy = h - floor(y * h);
if (x * x >= y) {
img.set(sx, sy, r);
++valid;
} else {
img.set(sx, sy, b);
}
}
img.updatePixels();
return valid / sampled;
}
function computePI(n) {
sampled += n;
var r = color(255, 0, 0);
var b = color(0, 0, 255);
for (var i = 0; i < n; ++i) {
var x = random() * 2 - 1;
var y = random() * 2 - 1;
var sx = floor((x / 2 + 0.5) * w);
var sy = floor((y / 2 + 0.5) * h);
if (x * x + y * y <= 1.0) {
img.set(sx, sy, r);
++valid;
} else {
img.set(sx, sy, b);
}
}
img.updatePixels();
return valid / sampled * 4;
}
function draw() {
background(255);
var value = computePI(100);
// var value = computeIntegral(100);
image(img, 0, 0);
console.log("sampled = " + sampled + " value = " + value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment