0

I'm from physics SE.

Recently I started learning Matlab and training on some simple functions, and now I have a serious problem with this one:

function [x,n] = newton( p,a,b,d )
%This function approximates a root of a polynomial in [a,b] with an error bound less than d. 
c=(a+b)/2;
q=polyder(p);
c1=c-polyval(p,c)/polyval(q,c);
n=1;
while c1-c > d
c=c1;
c1=c-polyval(p,c)/polyval(q,c);
n=n+1;
end
x=c1;
end

As you can see, it is a function that uses Newton's method to approximate a polynomial's root and gives the number of steps required. The problem is that it always gives wrong answers. I've tried it many times with different polynomials and intervals, and it always approached, never achieved, the required precision. Is there some mistake in the code that I'm not aware of ? Any help is appreciated.

1 Answer 1

2

When testing these kinds of iterative algorithms, you need to stop when the absolute value of the difference is less than your threshold - you are strictly checking the magnitude (which will often be negative).

function [x,n] = newton( p,a,b,d )
%This function approximates a root of a polynomial in [a,b] with an error bound less than d. 
c=(a+b)/2;
q=polyder(p);
c1=c-polyval(p,c)/polyval(q,c);

n=1;
while abs(c1-c) > d  %% put absolute values here
  c=c1;
  c1=c-polyval(p,c)/polyval(q,c); 
  n=n+1;
end

x=c1;
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.