Trying to get my output to be 22 decimal places

3 次查看(过去 30 天)
%Murphy Griffin
%ERG280-01
%December 3, 2021
function out=my_sin(x)
xrad=x*pi/180;
sign=1;
n=1;
total=0;
fact=1;
while abs(total-sin(xrad))>=10^(-22)
if n>200
break
end
total=total+(sign*((xrad^n)/(factorial(fact))));
fact=fact+2;
sign=sign*(-1);
n=n+2;
end
out=total;
end
I need the output of the fuction to be 22 decimal places but I cant use
digits(22)
vpa(my_sin(73))
to get to 22 decimal places. It needs to occur when I get my answer after inputting my_sin(73)
  1 个评论
Matt J
Matt J 2021-12-3
It needs to occur when I get my answer after inputting my_sin(73)
What's the difference?

请先登录,再进行评论。

回答(1 个)

David Hill
David Hill 2021-12-3
You cannot use floating point if you want 22 decimal places of accuracy, you must use symbolic.
function total=my_sin(x)
digits(22);
x=sym(num2str(x));
xrad=x*pi/180;
sign=1;
n=1;
total=sym(0);
fact=sym(1);
while abs(total-sin(xrad))>=1e-22
if n>200
break
end
total=total+(sign*((xrad^n)/(factorial(fact))));
fact=fact+2;
sign=sign*(-1);
n=n+2;
end
total=vpa(total);
end
  1 个评论
John D'Errico
John D'Errico 2021-12-3
+1. But to be picky, for SOME values of x...
sin(0)
ans = 0
really is EXACTLY correct, to even more than 22 decimal places. ;-)

请先登录,再进行评论。

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by