Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create MonteCarloDistribution.pde #95

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions introduction/MonteCarloDistribution/MonteCarloDistribution.pde
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Daniel Shiffman
// The Nature of Code
// http://www.shiffman.net

float[] vals;
float[] norms;

void setup () {
size (400, 300);

vals = new float[width];
norms = new float[width];
}

void draw () {
background(100);

float n = montecarlo();

int index = int (n * width);
vals[index]++;
stroke(255);

boolean normalization = false;
float maxy = 0.0;

for (int x = 0; x < vals.length; x++) {
line (x, height, x, height-norms[x]);
if (vals[x]>height) normalization = true;
if (vals[x]>maxy) maxy = vals[x];
}

for (int x = 0; x < vals.length; x++) {
if (normalization) norms[x] = (vals[x] / maxy) * (height);
else norms[x] = vals[x];
}
}

float montecarlo () {
boolean foundone = false;
int hack = 0;

while (!foundone && hack < 10000) {
float r1 = (float) random (1);
float r2 = (float) random (1);
float y = r1 * r1;

if (r2 < y) {
foundone = true;
return r1;
}

hack++;
}

return 0;
}