Using a while loop to solve a Taylor Series with approximate values.
Show older comments
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
Answers (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 Comments
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
on 14 Oct 2022
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
on 14 Oct 2022
VBBV
on 14 Oct 2022
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
on 14 Oct 2022
stephen
on 14 Oct 2022
stephen
on 14 Oct 2022
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].'
Categories
Find more on Particle & Nuclear Physics in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!