Error calculation and using for loop

6 ビュー (過去 30 日間)
MIAngie0973
MIAngie0973 2016 年 10 月 4 日
編集済み: elias GR 2016 年 10 月 4 日
The cosine function can be evaluated by the following infinite series: cos(x)=1-x^2/2!+x^4/4!-x^6/6!+... Create an M-file to compute cos(1.18 rad) for up to and including number of terms terms, which is up to the term x^8/8!. Your program should compute and display the values of cos x as each term in the series is added. then compute and display true relative error as a percentage..
attempted solution:
n=14;
x=pi;
terms=[0:2:n]
facts=factorial(terms);
x_power=x.^terms;
signs=(-1).^(terms/2);
quotes=x_power ./facts;
series=signs.*quotes;
m_cos_n=cumsum(series);
plot (m_cos_n);
true=-1.0;
p_error=(true-m_cos_n)/true*100;
plot(terms,(abs(p_error)));
  1 件のコメント
the cyclist
the cyclist 2016 年 10 月 4 日
What's your question?

サインインしてコメントする。

回答 (2 件)

Abhishek Jain
Abhishek Jain 2016 年 10 月 4 日
You can use the following code:
cosx=1;
x=1.18;
for i=1:4
cosx=cosx+(-1)^i.*x^(2*i)/factorial(2*i)
end
It prints the value of cos(x) after each step.

elias GR
elias GR 2016 年 10 月 4 日
編集済み: elias GR 2016 年 10 月 4 日
  1. You need to put your code inside a function, in order x and n to be parameters.
  2. You can estimate the true value by just using MATLAB's cos function.
  3. Add figure commands in order to see both plots.
  4. Usually we take the absolute value of the relative error.
  5. You need to take care if true=0 (not to divide by zero) - this is not included in the code below
function cosAppr(x,n)
terms=[0:2:n];
facts=factorial(terms);
x_power=x.^terms;
signs=(-1).^(terms/2);
quotes=x_power ./facts;
series=signs.*quotes;
m_cos_n=cumsum(series);
figure
plot (m_cos_n);
true=cos(x);
p_error=abs((true-m_cos_n)/true*100);
figure
plot(terms,(abs(p_error)));
end
You can call the function like
cosAppr(1.18,8)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by