How to create a sine function using a mid point break loop.

58 views (last 30 days)
Create a function called my_sin, using a midpoint break loop to approximate the value of sin(x). Determine convergence by comparing successive values of the summation as add additional terms. These successive sums should be within an abs value of 0.001 of each other.
I've tried:
function output = my_sin(x)
x=input('Enter value of x to calculate sin(x): ');
y(1)=x;
total(1)=x;
k=0;
n=0;
while k>=0
k = k+1;
y(k)=(((-1)^k)/(factorial(n)))*x^(n);
total(k) = y(k+1)-y(k);
if (abs(total(k))<=0.001)
break
end
SINX=sum(total);
n=n+2;
end
output = disp(SINX
But I get an error saying:
Attempted to access y(2); index out of bounds because numel(y)=1.
Error in my_sin (line 10)
total(k) = y(k+1)-y(k);
Any help with this would be great.
Thanks

Accepted Answer

Timothy Bell
Timothy Bell on 16 Jul 2014
I figured it out; here is in case anyone else would like to see.
function output = my_sin(x)
x=input('Enter value of x to calculate sin(x): ');
k=1;
n=3;
y(1)=x;
total(1)=y(1);
while k>=0
k=k+1;
y(k)=(((-1)^(k-1))/(factorial(n)))*x^((n));
total(k)=total(k-1)+y(k);
if (abs(total(k)-total(k-1))<=0.001)
break
end
n=n+2;
end
l=length(total);
output = total(l);
  1 Comment
Christopher Merrick
Christopher Merrick on 22 Oct 2015
It tells me I can't say function at the beginning. then won't finish running when I enter the value for x.

Sign in to comment.

More Answers (0)

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!