Why does Processing draw my sine wave in a samply way?

Viewed 239

I am trying to get Processing to draw a sine wave. However, it appears like a badly sampled version of a sine wave on the output. Do I need to replace the shape with a series of lines, or is there another solution?

I've tried casting the variable to a float, and changing c++ to c += 1.

  noFill();
  stroke(255);
  beginShape();
  translate(0, 100);
  for (int c = 0; c <= width; c += 1)
  {
    vertex(c, (float) 100 * sin(c / 50));
  }
  endShape();

I expect that it traverses the window pixel-by-pixel, creating a smooth shape. What I actually get is what appears to be sampled, as shown here.

Quantized sine wave

1 Answers

The expression

c / 50

is an integral division. The result is an integral value. If 0 <= c < 50, then the result is 0, if 50 <= c < 100 then the result 1.

To do a floating point division, with a floating point result, on of the 2 values has to be floating point (e.g. c / 50.0).

Change the expression to solve the issue:

vertex(c, 100.0 * sin((float)c / 50.0));

Related