While loop to calculate sine

1 次查看(过去 30 天)
Mary Jeppson
Mary Jeppson 2016-12-10
回答: the cyclist 2016-12-10
I have written this code that settles on an incorrect value and I can't see what's wrong. Can anyone show me?
x = pi/4;
analytical = sin(pi/4);
k = 1;
n = 2;
es = .5^(2-n);
et(1) = 1;
sumterms(1) = 0;
while et>=es
thisterm = (-1)^(k+1)*x^(k*2-1)/factorial(k*2-1);
sumterms(k+1) = thisterm + sumterms(k);
et(k+1) = abs(analytical-sumterms(k))/analytical*100;
k = k+1;
end
I don't want to abuse the 'Ask' feature of this site so let me know if I'm asking too many questions. The answers are helpful to me if as long as I'm not taking advantage. Thank you!

回答(1 个)

the cyclist
the cyclist 2016-12-10
I don't understand the significance of
es = .5^(2-n);
but that is a very lax accuracy criterion. es = 1 in your case, so you only have to calculate sin(pi/4) within 1!
I hard-coded
es = 0.0001;
and got a much more accurate value of sin(pi/4).

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by