Skip to content

Instantly share code, notes, and snippets.

@zach-klippenstein
Created October 29, 2009 05:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zach-klippenstein/221177 to your computer and use it in GitHub Desktop.
Save zach-klippenstein/221177 to your computer and use it in GitHub Desktop.
Various implementations of Netwon's method
public ResultPair solveNewton(double init, double epsilon)
{
int numIt = 1;
double root;
double xn;
double xnPlusOne;
double xnMinusOne;
xn = init;
xnPlusOne = xn - eval(xn) / getDeriv().eval(xn);
while(Math.abs(xnPlusOne - xn) >= epsilon)
{
xn = xnPlusOne;
xnPlusOne = xn - eval(xn) / getDeriv().eval(xn);
numIt++;
}
root = xnPlusOne;
ResultPair result = new ResultPair(root, numIt);
return result;
}
public ResultPair solveNewton (double init, double epsilon)
{
double[] x = new double[2]; // x_n and x_n+1, respectively
int i;
boolean finished = false;
x[0] = init;
for (i = 0; !finished ; i++)
{
// set x[n+1] by subtracting quotient of P(x[n]) and P'(x[n]) from x[n]
x[1] = x[0] - (eval(x[0]) / getDeriv().eval(x[0]));
// Check for root
if (Math.abs(x[1] - x[0]) < epsilon)
{
finished = true;
}
x[0] = x[1];
}
return new ResultPair(x[1], i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment