+2  A: 
x = m - abs(i % (2*m) - m)
Eric Bainville
+22  A: 

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 period 20 pi, oscillating between 3 and -3.


Update:

Curvy Triangular Wave

To get a variation of the triangular wave that has curves rather than straight lines, you just need to introduce an exponent into the equation to make it quadratic.

Concave curves (i.e. x^2 shape):

y = pow(abs((x++ % 6) - 3), 2.0);

Concave curves (i.e. sqrt(x) shape):

y = pow(abs((x++ % 6) - 3), 0.5);

Alternatively to using the pow function, you could simply define a square function and use the sqrt function in math.h, which would probably improve performance a bit.

Also, if you want to make the curves steeper/shallower, just try changing the indices.


In all of these cases you should easily be able to adjust constants and add scaling factors in the right places to give variations of the given waveforms (different periods, ampltiudes, asymmetries, etc.).

Noldorin
Note that my x does not correspond to your x in the question. The x I used here represents the conventional value along the x-axis, and similarly y represents the value along the y-axis. The x here seems to be the i in your question.
Noldorin
I could add these waveforms to get more complicated ones as well, yes?
willc2
Doesn't that triangular wave oscillate between 3 and *0*?
Keith Smith
@willc2: Yes, of course. :) If you're wondering how to get another specific waveform, just ask, and I can suggest something - these provide good starting blocks however.
Noldorin
@Keith: Well spotted - thanks. I've fixed that now.
Noldorin
nice answer. a pity that this isn't the accepted one, imho
Johannes Schaub - litb
@litb: Thanks... And yeah, I thought I had answered the question rather completely, but never mind.
Noldorin
+2  A: 
y = abs( amplitude - x % (2*amplitude) )

Changing the wavelength just needs a factor for x.

Edit: What I call amplitude is actually not the amplitude, but the maximum value (i.e. 5 if the curve oscillates betwen 0 and 5). The amplitude in the mathematical sense is half of that. But you get the point.

balpha
this results in a "V" wave; you'd need to add "y = m - y" to get a triangle wave
bubaker
A wave is usually considered infinite, making a "V wave" and a triangle wave essentially identical. But you're right in so far that if you want f(0) = 0, you have to do a shift.
balpha
A: 

Try this:

x = m - abs(m - 2*(i++ % m))
bubaker