Last active
August 29, 2015 14:19
-
-
Save voltrevo/92f898919bb11275f17d to your computer and use it in GitHub Desktop.
ES6 Newton Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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