My game needs to move by a certain angle. To do this I get the vector of the angle via sin and cos. Unfortunately sin and cos are my bottleneck. I’m sure I do not need this much precision. Is there an alternative to a C sin & cos and look-up table that is decently precise but very fast?
I had found this:
float Skeleton::fastSin( float x )
{
const float B = 4.0f/pi;
const float C = -4.0f/(pi*pi);
float y = B * x + C * x * abs(x);
const float P = 0.225f;
return P * (y * abs(y) - y) + y;
}
Unfortunately, this does not seem to work. I get significantly different behavior when I use this sin rather than C sin.
Thanks
For your
fastSin(), you should check its documentation to see what range it’s valid on. The units you’re using for your game could be too big or too small and scaling them to fit within that function’s expected range could make it work better.EDIT:
Someone else mentioned getting it into the desired range by subtracting PI, but apparently there’s a function called
fmodfor doing modulus division on floats/doubles, so this should do it:I have no idea how expensive
fmodis though, so I’m going to try a quick benchmark next.Benchmark Results
I compiled this with
-O2and ran the result with the Unixtimeprogram:The result is that
sinis about 1.8x slower (iffastSintakes 5 seconds,sintakes 9). The accuracy also seemed to be pretty good.If you chose to go this route, make sure to compile with optimization on (
-O2in gcc).