Trying to get my output to be 22 decimal places
3 views (last 30 days)
Show older comments
%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 Comment
Matt J
on 3 Dec 2021
It needs to occur when I get my answer after inputting my_sin(73)
What's the difference?
Answers (1)
David Hill
on 3 Dec 2021
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 Comment
John D'Errico
on 3 Dec 2021
+1. But to be picky, for SOME values of x...
sin(0)
really is EXACTLY correct, to even more than 22 decimal places. ;-)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!