Created
May 3, 2018 22:34
-
-
Save HunderlineK/18f520f0112309e72d9190051232a29c to your computer and use it in GitHub Desktop.
Newton Solver
This file contains hidden or 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
const paymentFactor = 0.0068; | |
const duration = 180; | |
const f = ((p, n) => x => | |
Math.pow(1 + x, n + 1) - (1 + p) * Math.pow(1 + x, n) + p)( | |
paymentFactor, | |
duration | |
); | |
const derivative = ((p, n) => x => | |
(n + 1) * Math.pow(1 + x, n) - n * (1 + p) * Math.pow(1 + x, n - 1))( | |
paymentFactor, | |
duration | |
); | |
const precision = 0.000001; | |
function newtonsMethod(guess = 0, prevGuess = 0) { | |
const withinPrecision = Math.abs(prevGuess - guess) < precision; | |
return withinPrecision || derivative(guess) === 0 | |
? guess | |
: newtonsMethod(guess - f(guess) / derivative(guess), guess); | |
} | |
const solution = newtonsMethod(0.2); | |
console.log(solution); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment