I have to write my own cosine function.
이전 댓글 표시
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
James Tursa
2019년 3월 8일
편집: James Tursa
2019년 3월 8일
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
답변 (1개)
KSSV
2019년 3월 8일
Note that you can represent the above series as follows:

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
Torsten
2019년 3월 8일
And work with y = mod(x,2*pi) instead of x.
James Tursa
2019년 3월 8일
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
카테고리
도움말 센터 및 File Exchange에서 Get Started with Signal Processing Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!