Line 9 is wrong. You're supposed to just assign the value of the expression to result, not increment result by the value of the expression.
That wouldn't be quite right either.
I believe empror9 is trying to take advantage of the fact that x²/2! * x²/(4!/2!) = x^4/4! and so on.
This doesn't work in practice, because result contains the sum of all elements so far, not just the last.
It works with a small change:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
float cos_taylor(float x)
{
float result = 1;
int limit = 20;
int sign = -1;
float last=1;
for(int i=2 ; i<limit ; i+=2,sign=-sign)
{
last*=(x*x)/(i*(i-1));
result += sign*last;
}
return result;
}
The 15th degree Taylor polynomial should be fairly accurate up to abs(1.5*pi), so there must still be some bug in your code.
If you need something that's accurate on the entire real line, though, why don't you just use the regular trigonometric functions, instead of their approximations?
When doing about 20-25 iterations, the approximation gives good results for the range -2π 2π, but not beyond that.
Surely you realize that cos and sin are periodic? And that is why you can use fmod to make sure x stays in that range.
By using fmod, you don't have to increase the number of iterations to get valid results for large x values.
But you've been told so on another forum already.