What is the problem with the following sin approximation?

3 views (last 30 days)
I am being asked to take two inputs and spit out an approximation of sine and how many terms were being used in the approx. Here is the code with a while loop.
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
real=sin(x);
n=1;
while threshold<abs((real-approx)/real)
if rem(n,2)==0
X1=1;
X2=0;
else
X2 = 1;
X1=0;
end
approx=approx+ X1*(x^(2*n-1)/factorial(2*n-1))-X2*(x^(2*n-1)/factorial(2*n-1))
n=n+1;
terms=terms+1
end
end
the sine approx is equal to sin(x) = x−x3/3!+x5/5! −x7/7!+···

Answers (1)

Thorsten
Thorsten on 1 Dec 2015
Edited: Thorsten on 1 Dec 2015
The formula is wrong. It's (-1)^(n)*x.^(2*n+1)/factorial(2*n+1) for the n'th term. Instead of your solution using X1 and X2, you can use (-1)^n:
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
  2 Comments
William Schmidt
William Schmidt on 1 Dec 2015
I just figured this out as you answered. Here's the code that worked for me
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
real=sin(x)
n=1;
while threshold<abs((real-approx)/real)
if rem(n,2)==0
X1=1;
X2=0;
else
X2 = 1;
X1=0;
end
n=n+1;
approx=approx+ X1*(x^(2*n-1)/factorial(2*n-1))-X2*(x^(2*n-1)/factorial(2*n-1))
terms=terms+1
end
end
Image Analyst
Image Analyst on 1 Dec 2015
Maybe you could Accept and Vote for his answer anyway, since his answer was right and he took the time to help you. It will give him "Reputation points" towards more powers in this forum.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!