Using Newton's Method to plot basin of attraction?

19 visualizzazioni (ultimi 30 giorni)
Erin W
Erin W il 27 Set 2016
Commentato: Christina Reed il 18 Feb 2018
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!

Risposte (1)

Matt J
Matt J il 27 Set 2016
Modificato: Matt J il 27 Set 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 Commenti
Erin W
Erin W il 30 Set 2016
Oh nevermind. I had it. I had one small problem. No worries!
Christina Reed
Christina Reed il 18 Feb 2018
Erin W, what did you do to get your code working? Doing similar problem but with for loops.

Accedi per commentare.

Categorie

Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by