Using Newton's Method to plot basin of attraction?
5 views (last 30 days)
Show older comments
Hi all,
So I have this question and these two codes: "The basin of attraction for a particular root p s the set of all numbers that, if used as initial guesses in Newton’s method, will cause the algorithm to converge to p. The polynomial f(x) = x 3 − 2x 2 − 11x + 12 has roots 4, −3, and 1. Write a function that creates an array x of 1, 000 initial guesses on the interval [−3, 4] and runs Newton’s method with tolerance 10−8 for each initial guess (remember to comment out any plot commands or print to screen commands in your newton.m or you may have 1000 plots come up). Store the root for each initial guess in the array p, and plot p against x (use a ylim([-5 5]) command to set the y axis). From your plot, what, approximately, is the basin of attraction for the root 1?"
This is my code for this assignment:
x = linspace(-3,4,1000);
tol = 10^-8;
f = @(x) (x^3-2*x^2-11*x+12);
df = @(x) (3*x^2-4*x-11);
p = zeros(length(x));
for j=-3:length(x)
p(j) = newton(p(j),tol,f,df);
end
ylim([-5,5]);
plot(x,p)
and here is my Newton Method code which works:
function [root,count] = newton(p0,tol,f,df)
dist = tol+1;
count = 0;
while dist>tol
if df(p0)==0
disp('root not found');
return
end
p1 = p0-(f(p0)/df(p0));
dist = abs(p1-p0);
p0 = p1;
count = count + 1;
end
root = p0;
count
My basinofattraction code does not work. It does not plot nor does it run through the loop. What am I missing?
Thanks!
0 Comments
Answers (1)
Matt J
on 27 Sep 2016
Edited: Matt J
on 27 Sep 2016
You do not appear to be using 'x' anywhere in the root calculations.
Also, starting your loop at j=-3 is probably a typo.
7 Comments
Christina Reed
on 18 Feb 2018
Erin W, what did you do to get your code working? Doing similar problem but with for loops.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!