Question

I am trying to draw a Gaussian curve with mean = 0 and standard deviation = 1 using processing, but when my code runs, nothing is drawn to the screen (not even the background).

Here is my code:

float x, y, mu, sigma;

void setup() {
  size(900, 650);
  background(255);
  stroke(0);
  strokeWeight(1);

  mu = 0.0;
  sigma = 1.0;

  for(int i = -4; i < 4; i += 0.5) {
    x = i;
    y = (1/(sigma * sqrt(2 * PI)))*(exp((-1 * sq(x - mu)) / (2 * sq(sigma)) ));

    x = map(x, -4, 4, 0, width);
    y = map(y, 0, 1, 0, height);
    point(x, y);
  }
}

void draw() {

}
Was it helpful?

Solution

In your for loop, you are using an int as the counter, but you're incrementing it by 0.5. When i is positive and it is incremented, that 0.5 gets truncated and i remains what is was before-- so the loop runs forever. It's a fun observation that i does increase when it is negative-- truncation works towards zero, so adding 0.5 ends up adding 1. Changing the declaration of i from int i = -4 to float i = -4 fixed it on my computer. You may also want to increase the stroke weight, at least temporarily, to verify that the points are being drawn (they were hard to see for me and I wasn't sure it was working at first).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top