Using a while loop to solve a Taylor Series with approximate values.
显示 更早的评论
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 个)
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 个评论
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_approx, err_approx, err_true, n];
end
n
y_approx
VBBV
2022-10-14
if you give intial value to y_approx and run the loop, you can see the resulting y_aapprox is found at the end of 200 iteration after while loop execution.
stephen
2022-10-14
VBBV
2022-10-14
You have applied the inequality operator for the condition in while loop. But if you notice it is less than ( < ) which makes the condition not satisfied at the beginning of loop itself since 100 > 0.5, So, you need to use a greater than (>) operator to satisfy the condition and execute the statements inside the while loop.
stephen
2022-10-14
stephen
2022-10-14
stephen
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].'
类别
在 帮助中心 和 File Exchange 中查找有关 Particle & Nuclear Physics 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!