Newton method to find polinom roots?
9 views (last 30 days)
Show older comments
Hi!
I wrote Newton method in matlab to find the polinom roots but I didn't get it which the answer write.
p = [ 1 -1 -6 0]
x0 = 2;
So this is my code:
function [pd,X] = newtonMethod(p,x0)
n = length(p);
pd = polyder(p)
result = [];
for i = 1:8
fx(i) = polyval(p,x0);
fdx(i) = polyval(pd,x0);
x(i) = x0 - (fx/fdx);
result = [result; x(i)];
x0 = x(i);
end
result
end
And i get this:
6.0000
4.4028
2.9345
1.4956
0.0557
-1.3792
-2.8141
-4.1472
But the answer:
6.0000
4.4000
3.4891
3.0912
3.0041
3.0000
3.0000
3.0000
0 Comments
Accepted Answer
More Answers (1)
John D'Errico
on 23 Nov 2018
Edited: John D'Errico
on 23 Nov 2018
+1 to Torsten, because his answer is completely correct and should be the one you accept. All this answer does is be a bit more explanatory.
You have posed a cubic polynomial.
p = [ 1 -1 -6 0]
p =
1 -1 -6 0
roots(p)
ans =
0
3
-2
So 3 roots you might find, at 0, 3, & -2.
If you start a solver out at x0 = 2, then you will converge to some root, though the root you will find will depend on the shape of the function itself and the start point.
ezplot(@(x) polyval(p,x),[-3,4])
refline(0,0)
So by starting at the point x0=2, Newton's method moves up to the root at 3 (though first bouncing as high as 6, then monotonically returning to 3). Had you started just a bit lower, say x0=1.5 or so, it should have converged to 0 as a root.
Now, what did you do incorrectly? Your code was not that far off. But you always used x0 in this expression:
x(i) = x0 - (fx/fdx);
So x0 never changes. Instead, you wanted to use the previous result, updating x0 on each iteration. That is what Torsten did to fix your code.
x0 = x0 - (fx/fdx);
and then saving the value of x0 at each iteration.
3 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!