Newton's Method in Matlab
91 views (last 30 days)
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
0 Comments
Accepted Answer
John D'Errico
on 27 Jan 2020
Edited: John D'Errico
on 27 Jan 2020
First, consider if you are trying to solve the wrong problem.
In your question, you state it as e^2*sin(x) - x = 0
However, in your code, you write exp(2*sin(x)) - x. You do realize there is a difference? What I don't know is if you have miswritten your question, or is it your code?
fun = @(x) exp(2)*sin(x) - x;
fplot(fun,[0,3])
yline(0);
fzero(fun,3)
ans =
2.7589
So the function you claim to want to solve has a zero around x==2.76, which is inconsistent with your claim of where the root lies. Next, look at the function you wrote code for:
fun = @(x) exp(2*sin(x)) - x;
fplot(fun,[-5,3])
yline(0);
Indeed, this does seem to have a root near 2.6357. So, just possibly, you really do want to solve the problem exp(2*sin(x))-x==0.
fzero(fun,3)
ans =
2.6357
But now, look at the plot! What happens when you start Newton's method at x==1? THINK! Where will the first iteration go? On which side of that hump is x==1?
The point is, Newton's method tries to drive the functino to zero. But if you start the iterations BELOW x==1.5028, which direction will Newton's method push you?
fminbnd(@(x) -fun(x),1,3)
ans =
1.5028
Think about the meaning of the iterations of Newton's method. What is the goal? What will happen?
2 Comments
See Also
Categories
Find more on Ordinary Differential Equations 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!