0

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() {

}
Cettt
  • 11,460
  • 7
  • 35
  • 58
mpjan
  • 1,790
  • 5
  • 18
  • 21
  • On a correct-code note: don't put all your draw code in `setup`. Take all the code you have after `size(...)`, and put that in `draw`, then add a `noLoop()` call as your second line in `setup` so that the code only runs once instead of continuously at the default frameRate. `setup` is for setup instructions for your sketch, prior to drawing things. Draw instructions may work, but it's not where they're supposed to go. – Mike 'Pomax' Kamermans Oct 08 '13 at 18:44

1 Answers1

2

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).

kevinsa5
  • 3,301
  • 2
  • 25
  • 28