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

19 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Timothy Bell
Timothy Bell el 16 de Jul. de 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 comentario
Christopher Merrick
Christopher Merrick el 22 de Oct. de 2015
It tells me I can't say function at the beginning. then won't finish running when I enter the value for x.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by