MATLAB: I’m attempting to write a function that calculates the value of sine using a taylor series to within a tolerance of 10^-6. I think the loop is set up correctly but i’m not sure the series equation is correct as the function never stops running.

homeworktaylor series

function [y] = homework11(x)
y1=0;
y=0;
tolerance=0.000001;
a=sin(x);
n=1;
while y<(a-tolerance)
y1(n)=y1+((-1).^(n))*(x.^(2*(n+1))/factorial(2*(n+1)));
n=n+1;
y=sum(y1);
end

Best Answer

You are close, but have a few errors. The errors are:
1) The exponent on x should be 2*n+1, but you have 2*(n+1), which isn't the same thing. Also same error for the factorial in the denominator.
2) The y1(n)=y1+etc stuff is not using y1 correctly on the right hand side. You shouldn't be adding y1 on the right hand side. The right hand side should just be the n'th term and nothing else.
3) You are missing the 0'th term in your sum since you start at n=1. To get the 0'th term you can simply add x to your current sum.
4) You don't have the correct stopping criteria in your while statement. You need to stop based on the difference between your estimate and the truth.
Correcting all of these errors gives:
function [y] = homework11(x)
y1=0;
y=0;
tolerance=0.000001;
a=sin(x);
n=1;
while abs(y-a)>tolerance % <-- Fixed (4)
y1(n)=((-1).^(n))*(x.^(2*n+1)/factorial(2*n+1)); % <-- Fixed (1) and (2)
n=n+1;
y=x+sum(y1); % <-- Fixed (3)
end