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

20 次查看(过去 30 天)
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

采纳的回答

Timothy Bell
Timothy Bell 2014-7-16
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 个评论
Christopher Merrick
Christopher Merrick 2015-10-22
It tells me I can't say function at the beginning. then won't finish running when I enter the value for x.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by