In a similar way that modulo generates a sawtooth wave. It doesn\'t have to be continuous.
here is what i mean:
int m = 10;
int x = 0;
int i
y = abs((x++ % 6) - 3);
This gives a triangular wave of period 6, oscillating between 3 and 0.
y = (x++ % 6) < 3 ? 3 : 0;
This gives a regular square wave of period 6, oscillating between 3 and 0.
y = 3 * sin((float)x / 10);
This gives a sine wave of period 20 pi
, oscillating between 3 and -3.
Update:
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.).
I know this is an old post but for anyone that is searching for something similar I recommend looking at. http://en.wikipedia.org/wiki/Triangle_wave
The last formula y(x)=(2a/π)arcsin(sin((2π/p)*x))
or.
(2 * amplitudeConstant / Math.PI) * Math.Asin(Math.Sin(2 * (Math.PI / periodConstant) * Convert.ToDouble(variableX)))
Here is a periodic function that looks like a distant sine approximation; essentially it's a Sinuating paraboloid, using X squared:
function xs ( xx : float ): float{
var xd =Mathf.Abs((Mathf.Abs(xx) % 2.4) - 1.2);
if ( Mathf.Abs(Mathf.Abs(xx) % 4.8) > 2.4){
xd=(-xd*xd)+2.88;
}else{
xd = xd*xd;
}
return xd;
}
x = m - abs(i % (2*m) - m)
Expanding on Eric Bainville's answer:
y = (A/P) * (P - abs(x % (2*P) - P) )
Where x is a running integer, and y the triangle wave output. A is the amplitude of the wave, and P the half-period. For instance, A=5 will produce a wave which goes from 0 to 5; P=10 will produce a wave with a period of 20. The wave starts at y=0 for x=0.
Note that y will be a floating-point number unless P is a factor of A. And, yes, for the mathematical purists: A is technically twice the amplitude of the wave, but look at the picture below and you'll understand what I mean.
Visualised:
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.