Using Newton's Method to plot basin of attraction?

조회 수: 18 (최근 30일)
Erin W
Erin W 2016년 9월 27일
댓글: Christina Reed 2018년 2월 18일
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에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by