Bell Curves

Demo: A quick Bell-Curve plotting algorithm.

The Problem

I wanted to find a fast way to plot a bell-curve or "normal-curve" with Processing.js (also known as Gaussian distribution). I needed to get this technique down to create a scalable Gaussian blur filter in Processing.js, so I started reading lots of documents and hunting through people's source code for examples I could convert.

Unfortunately for me: I paid very little attention in math class and kick myself when I see algebraic equations, knowing how much better a programmer I could be. So I found plenty of mysterious looking equations online... and plenty of code examples that dealt with Gaussian readings of randomly distrobuted data: blah!

The Solution

So in the end I had to resort to a somewhat relevant explanation, a ton of determination, trial and a huge mountain of error. So after hours & hours of reading and wanting to kick stuff, I finally pinned down a really useful way to draw a bell-curve across a given width and height, with as few lines of code as I could squeeze it in to. Knowing that there are probably hundreds of people out there (who are also wanting to kick stuff), I knew it made sense to document my findings. So here they are:

float x, y;
float val, sd, mean; 

void setup(){
  size(320, 240);
  stroke(255);
  background(100);
  x = 0; y = height;
  range = width;
  sd = height; // Standard Deviation - Omega
  mean = (range / sd); // Mean - Sigma      
}

void draw(){
  for (x=0; x < range; x++){      
    val = sq(sin(((x*PI) - mean) / (range)))*sd;
    point(x, y - val);
  }
}

Simple eh? Links would be much appreciated if you use my code.

Beakdown:

The width becomes the range of values which is iterated though and drawn at each point. The mean is the width multiplied by the height of the sketch and the standard deviation or "peak" is height of the sketch.

In this example I have used PI to draw both sides of the curve, but if you were just looking to return the position of randomly distributed values you could use HALF_PI instead.

Please use the form above to adjust the values and get a feel for what the algorithm can do.

Note: some of the draw methods I have included are not really related to Gaussian curves.