Newton's Method in Matlab
Show older comments
I am trying to create a function that implements Newton's Method to solve the equation
. I know from the past few questions that my zero should be close to x = 2.6357 when my initial guess x0 = 1. Any sort of advice would be helpful because at this point I do not produce any output in the first code and then I get 0.4109 from the second.
**Function 1:
function [y] = Newton3(x0)
a = @(x) exp(2*sin(x)) - x;
b = @(x) (2 * exp(2*sin(x))* cos(x)) - 1;
tol = 10^12;
x(1) = x0 - (a(x0) / b(x0));
er(1) = abs(x(1) - x0);
k = 2;
while (er(k-1) > tol) && (k <= 50)
x(k) = x(k-1) - (a(x(k-1)) / b(x(k-1)));
er(k) = abs(x(k) - x(k-1));
k = k + 1;
y = x(k);
end
end
**Function 2:
function [r] = Newton(x0)
a = @(x) exp(2*sin(x)) - x;
b = @(x) (2 * exp(2*sin(x))* cos(x)) - 1;
tol = 10^-12;
x = x0;
for k = 1:50
y = x0;
x = y - (a(x) / b(x));
if abs(a(k)) <= tol
break
end
end
r = x;
end
Accepted Answer
More Answers (1)
Did you check whether the while loop is ever executed, even once? I don't think it is.
Categories
Find more on Variables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
