triangleWave function

double triangleWave(
  1. double x
)

Triangle wave function

The triangle wave function generates a periodic waveform that oscillates in a triangle shape.

Example:

print(triangleWave(2.7));  // Output: -0.8
print(triangleWave(3.2));  // Output: 0.8

The output for 2.7 is -0.8 and for 0.8 is -0.6 because the triangle wave function oscillates in a triangle shape.

Implementation

double triangleWave(double x) {
  x %= 1;
  if (x < 0.25) {
    return 4 * x;
  } else if (x < 0.75) {
    return -4 * x + 2;
  } else {
    return 4 * x - 4;
  }
}