# Matlab Newton's Method

## Homework Statement

So, I've written a program that carries out Newton's method. The root of the equation which I am trying to find is approximately 13.1. This is fine and my program returns the correct value when my initial guess is around this value (up to about x = 50 as my initial guess), however when I start using values such as 100+ it returns a complex root. The real part will be approximately 13.1 and the imaginary part will be VERY close to 0. Why is this and is there any way that I can fix/safeguard against this? Thanks.

## The Attempt at a Solution

Code:
function xnew = Newton (f, df, xi, tol)
xold = xi; %x(old) is assigned the value of the initial guess.
xnew = xold - f(xold)/df(xold); %Implement newtons method to find x(new).
k = 0; %Assigns k(the counter) an initial value.
fprintf('\nTable of Iteration No.(k) and Depth(h)\n')
fprintf('\nIteration No.\tDepth\n')
fprintf('%5u\t\t%2.6e\n',k,xi)

while ((abs(xnew - xold))/(abs(xnew)) > tol) %Running condition.
if (k <= 100) %Max number of iterations.
xold = xnew; %x(old) get's x(new)'s calculated value as per Newton Method's.
xnew = xold - f(xold)/df(xold);
k = k + 1; %Increment k.
else
warning('Maximum number of iterations has been reached')
break;
end
fprintf('%5u\t\t%2.6e\n',k,xnew)
end