Search code examples
c++loopsfor-loopgeometrysine-wave

Is There a Triangle Wave Function?


in a for-loop with % to get a saw function, for example using a period of 5 printing 2 cycles would look like this:

for(auto i = 0; i < 5 * 2; ++i) cout << i % 5 << endl;

Results in:

0
1
2
3
4
0
1
2
3
4

I want a function returns a triangle wave, so for some function foo:

for(auto i = 0; i < 5 * 2; ++i) cout << foo(i, 5) << endl;

Would result in:

0
1
2
1
0
0
1
2
1
0

Is there such a function, or do I need to come up with my own?


Solution

  • I thought we should at least post the correct answer here before this question is closed cause it is a duplicate.

    Eric Bainvile's answer is the correct one.

    int foo(const int position, const int period){return period - abs(position % (2 * period) - period);}
    

    However this gives a triangle wave with a range from [0, period] and a frequency of 2 * period and I want a range from [0, period / 2] and a cycle of period. This can be accomplished by just passing half of the period to foo or by adjusting the function:

    int foo(const int position, const int period){return period / 2 - abs(position % period - period / 2);}
    

    With such a simple function inlining seems preferable though so our final result will be:

    for(auto position = 0; position < 5 * 2; ++position) cout << 5 / 2 - abs(position % 5 - 5 / 2) << endl;
    

    Yielding the requested:

    0
    1
    2
    1
    0
    0
    1
    2
    1
    0