Triangular wave
y = abs((x++ % 6) - 3);
This gives a triangular wave of period 6, oscillating between 3 and 0.
Square wave
y = (x++ % 6) < 3 ? 3 : 0;
This gives a regular square wave of period 6, oscillating between 3 and 0.
Sine wave
y = 3 * sin((float)x / 10);
This gives a sine wave of a period of 20 pi , oscillating between 3 and -3.
Update:
Solid triangular wave
To get a variation of a triangular wave that has curves rather than straight lines, you just need to enter the exponent into the equation to make it quadratic.
Concave curves (i.e. form x^2 ):
y = pow(abs((x++ % 6) - 3), 2.0);
Concave curves (i.e. sqrt(x) form):
y = pow(abs((x++ % 6) - 3), 0.5);
Alternatively, using the pow function, you can simply define the square function and use the sqrt function in math.h , which will probably improve performance a bit.
Also, if you want to make the curves steeper / finer, just try changing the indices.
In all these cases, you should easily adjust the constants and add scaling factors to the desired places to give variations to the waveform data (different periods, amplitudes, asymmetries, etc.).
Noldorin Jul 02 '09 at 10:28 2009-07-02 10:28
source share