Skip to content

Instantly share code, notes, and snippets.

@robbrit
Created February 15, 2012 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robbrit/1838428 to your computer and use it in GitHub Desktop.
Save robbrit/1838428 to your computer and use it in GitHub Desktop.
Fractal series
function rnorm(mean, sd){
if (mean === undefined){
mean = 0;
}
if (sd === undefined){
sd = 1;
}
do {
var x1 = 2.0 * Math.random() - 1.0;
var x2 = 2.0 * Math.random() - 1.0;
var w = x1 * x1 + x2 * x2;
} while (w >= 1.0);
w = Math.sqrt( -2.0 * Math.log(w) / w);
return x1 * w * sd + mean;
}
function rcauchy(){
var n1 = rnorm();
var n2 = rnorm();
while (n2 == 0.0){
n2 = rnorm();
}
return n1 / n2;
}
function fract(arr, sd, a, b, depth){
if (a >= b - 1 || depth <= 0){
return;
}
var breakpoint = Math.random();
var mid = Math.floor(breakpoint * (b - a) + a);
if (mid == a){
mid++;
breakpoint = (mid - a) / (b - a);
}
var r;
switch(document.getElementById("method").value){
case "uniform":
r = (Math.random() - 0.5) * sd * Math.sqrt(12);
break;
case "gaussian":
r = rnorm() * sd;
break;
case "cauchy":
r = rcauchy() * sd;
break;
}
arr[mid] = (arr[b] - arr[a]) / (b - a) * (mid - a) + arr[a];
arr[mid] += Math.floor(r);
fract(arr, sd, a, mid, depth - 1);
fract(arr, sd, mid, b, depth - 1);
return;
}
function draw(){
var cvs = document.getElementById("canvas");
var ctx = cvs.getContext("2d");
var n = 500;
var arr = new Array(n);
arr[0] = parseInt(document.getElementById("start").value);
arr[n - 1] = parseInt(document.getElementById("end").value);
var sd = parseFloat(document.getElementById("sd").value);
fract(arr, sd, 0, n - 1, 100);
ctx.fillStyle = "white";
ctx.fillRect(0, 0, 500, 500);
// draw the series
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.moveTo(0, arr[0]);
for (var i = 1; i < n; i++){
if (arr[i] != undefined){
ctx.lineTo(i, arr[i]);
}
}
ctx.stroke();
// draw average values
ctx.beginPath();
ctx.strokeStyle = "red";
ctx.moveTo(0, arr[0]);
var sum = arr[0];
for (var i = 1; i < n; i++){
if (arr[i] != undefined){
sum += arr[i];
ctx.lineTo(i, Math.floor(sum / (i + 1)));
}
}
ctx.stroke();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment