Skip to content

Instantly share code, notes, and snippets.

@voltrevo
Last active August 29, 2015 14:19
Show Gist options
  • Save voltrevo/92f898919bb11275f17d to your computer and use it in GitHub Desktop.
Save voltrevo/92f898919bb11275f17d to your computer and use it in GitHub Desktop.
ES6 Newton Demo
"use strict"
const newton = ({
f,
df,
initialGuess,
tolerance = Number.EPSILON,
maxIterations = 1000
}) => {
let x = initialGuess;
let iterations = 0;
while (true) {
let lastX = x;
x -= f(x) / df(x);
iterations++;
let reachedTolerance = Math.abs(x - lastX) < tolerance;
if (
reachedTolerance ||
iterations >= maxIterations
) {
return [x, reachedTolerance];
}
}
};
let [sqrt2, success] = newton({
f: x => x * x - 2,
df: x => 2 * x,
initialGuess: 17
});
console.log(sqrt2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment