Skip to content

Instantly share code, notes, and snippets.

@jverkoey
Created March 21, 2014 21:08
Show Gist options
  • Save jverkoey/9696550 to your computer and use it in GitHub Desktop.
Save jverkoey/9696550 to your computer and use it in GitHub Desktop.
Newton's Method
// A quick-and-dirty implementation of Newton's method. Could use some tlc. May loop infinitely for certain inputs.
typedef CGFloat (^CalculateEquationBlock)(CGFloat x);
CGFloat NIFindRoot(CalculateEquationBlock fn, CalculateEquationBlock fndx, CGFloat guess) {
CGFloat root = guess;
while (1) {
CGFloat newRoot = root - fn(root) / fndx(root);
if (fabsf(newRoot - root) < 0.001) { // or whatever epsilon you want
return newRoot;
}
root = newRoot;
}
return root;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment