Is there a one-line function that generates a triangle wave?

后端 未结 8 1752
暗喜
暗喜 2020-12-02 04:59

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         


        
8条回答
  •  被撕碎了的回忆
    2020-12-02 05:21

    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.).

提交回复
热议问题