Mathworks Interview Question
Applications DevelopersCountry: United States
Interview Type: Phone Interview
To expand this answer, sin(x) is approximated as x - x^3/3! + x^5/5! - x^7/7! + ... to some number of terms that allow sufficient precision. cos(x) is approximated as 1 - x^2/2! + x^4/4! - x^6/6! +... . These formulas come from calculus.
To minimize the magnitude of the error incurred when approximating, angles are first reduced to the range [-pi, pi] and only then approximated using the above formulas. This can significantly reduce error because of the high powers of x in some of the terms. The formula doesn't start to converge very well until you have a number of terms that is somewhat proportional (give or take) to the absolute value of x. If you have -pi <= x <= pi, you're guaranteed that the formula does a pretty good job of converging after about just 5-10 terms.
we use series expansion of sine and cosine,as
sin(x) = x - x^3/3! + x^5/5! - x^7/7! + .....
cos(x) = 1-x^2/2! + x^4/4! - x^6/6! + .....
we calculate both power of x and factorial by power methods,
for example in cos series we first calculate x^2, then each time we just multiply x^2 with current maximum power to get next element.
similarly for sin series also we use the same fact.
Note that here x is in radian.
complexity : approx O(1), or it depends upon accuracy required.
A very good answer to this question from stackoverflow
First, you have to do some sort of range reduction. Trig functions are periodic, so you need to reduce arguments down to a standard interval. For starters, you could reduce angles to be between 0 and 360 degrees. But by using a few identities, you realize you could get by with less. If you calculate sines and cosines for angles between 0 and 45 degrees, you can bootstrap your way to calculating all trig functions for all angles.
Once you've reduced your argument, most chips use a CORDIC algorithm to compute the sines and cosines. You may hear people say that computers use Taylor series. That sounds reasonable, but it's not true. The CORDIC algorithms are much better suited to efficient hardware implementation. (Software libraries may use Taylor series, say on hardware that doesn't support trig functions.) There may be some additional processing, using the CORDIC algorithm to get fairly good answers but then doing something else to improve accuracy.
There are some refinements to the above. For example, for very small angles theta (in radians), sin(theta) = theta to all the precision you have, so it's more efficient to simply return theta than to use some other algorithm. So in practice there is a lot of special case logic to squeeze out all the performance and accuracy possible. Chips with smaller markets may not go to as much optimization effort.
Using taylor series approximation ( this is the exact method which is used in math libraries of programming languages )
- Cerberuz December 28, 2012