Created
April 29, 2011 23:33
-
-
Save sarnesjo/949232 to your computer and use it in GitHub Desktop.
Branch-free triangle wave generator functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
// assumes abs is branch-free | |
// see http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs | |
int triangle_wave_gen0(int i, int max_value) // min_value fixed to 0 | |
{ | |
i += max_value; | |
i %= max_value * 2; | |
i -= max_value; | |
i = abs(i); | |
return i; | |
} | |
int triangle_wave_gen(int i, int min_value, int max_value) | |
{ | |
return triangle_wave_gen0(i, max_value - min_value) + min_value; | |
} | |
int main() | |
{ | |
for(int i = 0; i < 12; ++i) | |
printf("#%d: %d\n", i, triangle_wave_gen(i, 10, 15)); | |
for(int i = 0; i < 12; ++i) | |
printf("#%d: %d\n", i, triangle_wave_gen0(i, 5)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment