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.
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.
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!
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.