Last active
May 23, 2019 16:55
-
-
Save jdmichaud/d2ba00bf65adc0d6e0676fb9da01e1c3 to your computer and use it in GitHub Desktop.
Newton's method
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
// Newton's method as explained here: https://youtu.be/U0xlKuFqCuI?t=290 | |
// To be used in the console of http://linalg.novidee.com or any environment with mathjs | |
function deriv(fcode, a, step = 0.01) { | |
return (fcode.eval({ x: a + step }) - fcode.eval({ x: a })) / step; | |
} | |
function newton(f, precision, seed = 0) { | |
const fcode = math.parse(f).compile(); | |
// This is not optimal as we evaluate twice the function at seed here and in deriv | |
const fa = fcode.eval({ x: seed }); | |
const dfdx = deriv(fcode, seed); | |
const res = -fa / dfdx + seed; | |
if (Math.abs(fcode.eval({ x: res })) > precision) { | |
return newton(f, precision, res); | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment