diff --git a/0. Randomness/6. Levy Flight Walker/index.html b/0. Randomness/6. Levy Flight Walker/index.html new file mode 100644 index 0000000..c390616 --- /dev/null +++ b/0. Randomness/6. Levy Flight Walker/index.html @@ -0,0 +1,15 @@ + + + + + + + +
+
+ + diff --git a/0. Randomness/6. Levy Flight Walker/sketch.js b/0. Randomness/6. Levy Flight Walker/sketch.js new file mode 100644 index 0000000..85e182d --- /dev/null +++ b/0. Randomness/6. Levy Flight Walker/sketch.js @@ -0,0 +1,55 @@ +// An algorithm for picking a random number based on monte carlo method +function acceptreject(formula) { + // We do this “forever” until we find a qualifying random value. + while (true) { + // Pick a random value. + let r1 = random(1); + // Assign a probability. + let probability = formula(r1); + // Pick a second random value. + let r2 = random(1); + + //{!3} Does it qualify? If so, we’re done! + if (r2 < probability) { + return r1; + } + } +} + +class Walker { + constructor(x = 0, y = 0) { + this.x = x + this.y = y + } + + step() { + let step = 1; + if (acceptreject(x => x*x) < 0.1) { + step = 20; + } + + let dx = random(-step, step); + let dy = random(-step, step); + + this.x += dx + this.y += dy + } + + draw() { + stroke(0) + point(this.x, this.y) + } +} + +let walker + +function setup() { + createCanvas(640, 240) + background(255) + walker = new Walker(320, 120) +} + +function draw() { + walker.step(); + walker.draw(); +}