Using a while loop to solve a Taylor Series with approximate values.
12 次查看(过去 30 天)
显示 更早的评论
f = atan(1);
n = 0;
i = -1;
err_approx = 100;
while (err_approx<=.5)
i = i + 2;
y_prev = y_approx
y_approx = (-1)^(i)(1/i+2)*1^(i+2)
err_approx = abs((y_approx-y_prev)/y_prev)*100
err_true = abs((y_approx-f)/f)*100
n = n + 1
[y_approx, err_approx, err_true, n]
end
This is my current code. I am using it to solve the taylor series expansion with approximate values to solve for arctan(1). I am having 2 errors. It is stating y_approx is undefined, and there is no output.
the expansion is in the form -x+x^(3)/3-x^(5)/5+x^(7)/7
Thanks in advance
0 个评论
回答(1 个)
VBBV
2022-10-14
编辑:VBBV
2022-10-14
f = atan(1);
n = 0;
i = -1;
err_approx = 100;
while (err_approx >= .5) % check the condition here
i = i + 2;
y_approx = ((-1)^(i))*(1/(i+2))*1^(i+2)
y_prev = y_approx;
err_approx = abs((y_approx-y_prev)/y_prev)*100
err_true = abs((y_approx-f)/f)*100;
n = n + 1
[y_approx, err_approx, err_true, n];
end
y_approx
Use a inequality opertor which satisfies the condition for while loop.
In your code, while loop is not satisfied, hence you get an error
8 个评论
VBBV
2022-10-14
f = atan(1);
n = 0;
i = -1;
err_approx = 100;
y_approx = 0; % give an initial value for y_approx
while (err_approx >= .5) % check the condition here
i = i + 2;
y_prev = y_approx;
y_approx = ((-1)^(i))*(1/(i+2))*1^(i+2);
err_approx = abs((y_approx-y_prev)/y_prev)*100;
err_true = abs((y_approx-f)/f)*100;
n = n + 1;
Y_p(n) = y_approx;
E_p(n) = err_approx;
E_t(n) = err_true; % error
N(n) = n; % iter
end
[Y_p;E_p;E_t;N].'
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!