MATLAB: While loop runs infinitely

loopMATLABtaylor serieswhile loop

I'm trying to create a function that takes two parameters: x and threshold. X is the angle and the threshold is the percent error I need to get when approximating sine with the taylor series. However my while loop runs infinitely and I'm very confused as to how do go about fixing it.
Here's what I have so far.
function [approx, terms] = approx_sine(x, threshold)
approx = x; % Initial approximation
terms = 0; % Number of additional terms added to improve the approximation;
% Write your code here using a while loop to improve the above approximation
while threshold <= abs((sin(x)-approx)/sin(x))
terms = terms + 2;
approx = (-1)^(terms+1)*(x.^terms)/ factorial(terms)+x;
end
end

Best Answer

The code for approximation is wrong. There are some errors in your formula: term takes values 0, 2, 4, ... but should take values 1,3,5,7; the (-1)^n changes sign with every new term, but since your term is always even, (-1)^(term+1) is always odd; and finally you add the n'th approximation term to the initial approximation x, instead of adding it to the most recent approximation.
This works
function [approx, n] = approxsine(x, threshold)
approx = x; % Initial approximation
n = 0; % Number of additional terms added to improve the approximation;
% Write your code here using a while loop to improve the above approximation
while threshold <= abs((sin(x)-approx)/sin(x))
n = n + 1;
approx = approx + (-1)^(n)*x.^(2*n+1)/factorial(2*n+1);
end
end