Implementing Taylor Series for sine and cosine in C

Anything over 12! is larger than can fit into a 32-bit int, so such values will overflow and therefore won’t return what you expect.

Instead of computing the full factorial each time, take a look at each term in the sequence relative to the previous one. For any given term, the next one is -((x*x)/(flag_2*(flag_2-1)) times the previous one. So start with a term of x, then multiply by that factor for each successive term.

There’s also a trick to calculating the result to the precision of a double without knowing how many terms you need. I’ll leave that as an exercise to the reader.

Leave a Comment