help me --> Taylor series cos(x)
22 次查看(过去 30 天)
显示 更早的评论
cos(x) The value of can be represented by the following series.
--> cos(x) = 1 - 1-x^2/2!+x^4/4!-x^6/6! + . . . .
1. Write a mycos function that uses the above series to obtain the value of cos(x).
2. For the difference between the value of cos(2) and mycos(2) provided in Matlab to be 0.001 or less,
Write a code to determine the minimum number of terms of the critical series.
3. Configure the maximum number of iterations to be less than 10.
I'd like to know the matlab code for this problem. Please help me.
My English may be poor and my grammar may be wrong.
function cos(x) = mycos(x,n)
12 个评论
采纳的回答
Jan
2021-5-14
编辑:Jan
2022-12-8
Then split the question into parts and solve them one by one.
- "Write a mycos function"
function y = mycos(x)
end
2. "above series to obtain the value of cos(x)"
function y = mycos(x)
y = 1 - x^2 / factorial(2) + x^4 / factorial(4) - x^6 / factorial(6);
end
This should be expanded in a loop:
function y = mycos(x)
y = 0;
for k = 0:10
y = y + (-1)^k * x^(2*k) / factiorial(2*k);
end
end
But why stop at k==10 oder anyother specific value?
"value of cos(2) and mycos(2) provided in Matlab to be 0.001 or less"
function [y, k] = mycos_2()
realY = cos(2);
y = 0;
k = 0;
while abs(y - realY) > 0.001
y = y + (-1)^k * x^(2*k) / factorial(2*k);
k = k + 1;
end
end
"Configure the maximum number of iterations to be less than 10."
function [y, k] = mycos_2()
realY = cos(2);
y = 0;
k = 0;
while abs(y - realY) > 0.001 && k < 10
% ^^^^^^^^^
y = y + (-1)^k * x^(2*k) / factorial(2*k);
k = k + 1;
end
end
Fine. But without reading the documentation and to understand how Matlab works, such a solution is completely useless. Do you see it? This wastes your time only.
2 个评论
Jan
2021-5-19
"[y, k]" is the output of the function. So the caller can know, how many iterations have been needed.
It does not matter, if you run a loop from 0 to n-1 and use k as value, or if the loop goes from 1 to n and k-1 is used. Both methods produce the same numbers.
更多回答(1 个)
Mahaveer Singh
2021-5-19
编辑:Mahaveer Singh
2021-5-19
% n is required length of series.Give initial value of n as your imagination to speed up of %calculation.
function y = mycos(x,n)
y = 0;
for i= 0:2:2*n
y = y + ((-1)^(i/2)) *(x^(i)) / factiorial(i);
end
end
while y-cos(x)>0.001
n=n+1;
y=mycos(x,n);
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Parallel Computing Fundamentals 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!