2

I've been asked to calculate the value for sin(x) using C++ without using any math libraries. How would I go about taking an entry by them (say 2 radians) and giving them back the value of a sin function at 2?

Thanks.

Axxelsian
  • 787
  • 3
  • 9
  • 25
  • 3
    This question appears to be off-topic because it is about maths – John3136 Oct 22 '13 at 00:40
  • possible duplicate of [How do Trigonometric functions work?](http://stackoverflow.com/questions/345085/how-do-trigonometric-functions-work) – Jerry Coffin Oct 22 '13 at 00:42
  • 1
    Why can't you use the math libraries? That's what they're for, and they will probably be much better than anything you come up with. (For one thing, they will probably be hardware accelerated.) – Raymond Chen Oct 22 '13 at 02:07

2 Answers2

7

One option would be to use the Taylor series for sine to get an approximation:

sin(x) = x - x3 / 3! + x5 / 5! - x7 / 7! + x9 / 9! - ...

If you evaluate the first five or six terms of this polynomial and x is small, you'll probably get a very good approximation for sin x. You could keep x small by trying to keep it in the range (-π, +π).

There are much better approaches available. One standard one is to use CORDIC, a set of approaches optimized to be fast and accurate.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Excellent, thanks. I had completely forgotten about utilizing the Taylor Series. – Axxelsian Oct 22 '13 at 00:47
  • Taylor series are a poor way to approximate functions because they converge slowly and have increasing error away from the central point. [Minimax polynomials are better.](http://stackoverflow.com/questions/12678277/in-what-situation-would-a-taylor-series-for-a-polynomial-be-necessary/12695691#12695691) A simple core `sin` implementation is [here](http://stackoverflow.com/questions/11261170/c-and-maths-fast-approximation-of-a-trigonometric-function/11575574#11575574). – Eric Postpischil Oct 23 '13 at 19:47
1

You could look into numerical approximation using Taylor Series. Less specifically you can read up on generalized Taylor/MacLaurin Series

In short:

sin(x) = x − x^3/3! + x^5/5! − x^7/7! + x^9/9!

Usually you can expand it to a couple terms and its within reasonable error range. The error falls off exponentially so you will have an accurate result with even 4, 5, or 6 terms. The more terms, the more accurate.

This is one way a computer can evaluate trigonometric functions, integrals, and many other complex formulae. I imagine whoever asked you is aiming towards bringing some understanding of the way computers handle these functions.

Farmer Joe
  • 6,020
  • 1
  • 30
  • 40