Taylor Series cosx function
4 views (last 30 days)
Show older comments
Use the Taylor Series cos x = 1-x^2/2!+x^4/4!-x^6-6!+x^8/8!+..... to write a program to compute cos x correct to four decimal places (x is in radians). See how many terms are needed to get 4-figure agreement with the MATLAB build-in function cos x.
4 Comments
James Tursa
on 3 Apr 2015
Edited: James Tursa
on 3 Apr 2015
Adding to John's comment, I would note that this series can become useless fairly quickly as x gets "large" because the large intermediate sums amass huge cancellation errors, yielding garbage for results. At the very least, one would need to rely on the knowledge that cos is periodic and adjust the input with some type of mod operation before feeding it into this series. However, a good method for this up-front mod operation is not at all trivial. Using a naive mod method can result in a lousy input value which will yield a garbage result compared to MATLAB.
MATLAB has a very sophisticated method of doing this mod operation internally that basically preserves all of the significant digits down to 1e-17 even if the input is relatively large. E.g., an extreme example:
>> x = 1e16 % relatively large input
x =
1.000000000000000e+16
>> cos(x)
ans =
-0.626168198133086
>> xm = mod(x,2*pi) % naive mod operation
xm =
2.637242432414304
>> cos(xm)
ans =
-0.875488657479139 % garbage result
>> digits 50 % set up for extra digits in arithmetic
>> vx = vpa('1e16')
vx =
10000000000000000.0
>> v2pi = 2*vpa('pi')
v2pi =
6.2831853071795864769252867665590057683943387987502
>> k = floor(vx/v2pi)
k =
1591549430918953
>> vxm = vx - k * v2pi % extended digit "mod" equivalent operation
vxm =
2.2474252491623665482579555800417389331267475864972
>> cos(double(vxm))
ans =
-0.626168198133086 % good result
As you can see from the above, the naive mod when used with large inputs gave garbage results when compared to MATLAB's internal method. And MATLAB's internal method, whatever it is, basically mimics all of this extra precision arithmetic shown above to get its result.
Based on this, one simple way to do a mod(x,2*pi) operation in MATLAB using the same background methods that MATLAB uses is as follows:
function y = mod2pi(x) % Result is in range -pi to +pi
y = atan2(sin(x),cos(x));
% To force the result in 0 to 2pi, uncomment the following lines
% g = y < 0;
% y(g) = y(g) + 2*pi;
end
John D'Errico
on 3 Apr 2015
This is usually called range reduction, reducing the set of values x for which the series must be expected to operate over.
Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!