Skip to content

Instantly share code, notes, and snippets.

@HunderlineK
Created May 3, 2018 22:34
Show Gist options
  • Save HunderlineK/18f520f0112309e72d9190051232a29c to your computer and use it in GitHub Desktop.
Save HunderlineK/18f520f0112309e72d9190051232a29c to your computer and use it in GitHub Desktop.
Newton Solver
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