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

回答(1 个)

VBBV
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 = -0.3333
err_approx = 0
n = 1
y_approx
y_approx = -0.3333
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
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].'
ans = 200×4
-0.3333 Inf 142.4413 1.0000 -0.2000 40.0000 125.4648 2.0000 -0.1429 28.5714 118.1891 3.0000 -0.1111 22.2222 114.1471 4.0000 -0.0909 18.1818 111.5749 5.0000 -0.0769 15.3846 109.7942 6.0000 -0.0667 13.3333 108.4883 7.0000 -0.0588 11.7647 107.4896 8.0000 -0.0526 10.5263 106.7013 9.0000 -0.0476 9.5238 106.0630 10.0000

请先登录,再进行评论。

类别

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