Using Newton's Method to plot basin of attraction?

8 次查看(过去 30 天)
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!

回答(1 个)

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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by