I have to write my own cosine function.

6 views (last 30 days)
I have to write my own cosine function using taylor series with inputs x and N for the degree. So i have figured out how to do the for loops for the n but the taylor series for cosine is
1-(x.^2/2!)+(x.^4/4!)-(x.^6/6!)...etc
so, my question is what can i use in my function to alternate between subtracting and adding after every loop. Sorry if i make no sense i am failry new to programming. thank you!!!
  1 Comment
James Tursa
James Tursa on 8 Mar 2019
Edited: James Tursa on 8 Mar 2019
You can use (-1)^some_power to get the alternating signs, but perhaps a more simple approach is to have a variable that simply flips signs each iteration. E.g.,
the_sign = 1;
for k=1:N
% other code here
your_term = the_sign * other_stuff;
% other code here
the_sign = -the_sign; % <-- flips signs each iteration
end

Sign in to comment.

Answers (1)

KSSV
KSSV on 8 Mar 2019
Note that you can represent the above series as follows:
Capture.PNG
With the above it makes easy to write your function.
As this is an home work problem..I am giving you a hint..not the complete code.
x = pi/4 ;
n = 100;
c = 0 ;
for i = 0:n
% Write your formula here
end
  2 Comments
Torsten
Torsten on 8 Mar 2019
And work with y = mod(x,2*pi) instead of x.
James Tursa
James Tursa on 8 Mar 2019
Not really in scope for this thread, but if you want to effectively use the same mod 2pi that MATLAB uses (which is some type of sophisiticated extended precision algorithm that is part of the trig library code):
xmod2pi = atan2(sin(x),cos(x));
To see the difference for large values:
>> x = 1e16
x =
1.000000000000000e+16
>> xmod2pi = atan2(sin(x),cos(x))
xmod2pi =
2.247425249162367
>> mod(x,2*pi)
ans =
2.637242432414304
>> sin(x)
ans =
0.779688006606979
>> sin(xmod2pi)
ans =
0.779688006606979
>> sin(mod(x,2*pi))
ans =
0.483238668387966

Sign in to comment.

Categories

Find more on Cartesian Coordinate System Conversion in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!