Created
October 3, 2018 00:20
-
-
Save glmdev/fe84cd6e7fb4fa96ffab1f02108a89aa to your computer and use it in GitHub Desktop.
A Javascript function to run a Newton's Method sequence
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 newton = (x0, fn, derivative, precision=3, array=false) => { | |
const estimates = [x0] | |
let next, last, variation = 1 | |
while ( variation > (Math.pow(10, (-1 * precision))) ){ | |
last = estimates.slice(-1)[0] | |
next = last - (fn(last)/derivative(last)) | |
estimates.push(next) | |
variation = Math.abs(next-last) | |
} | |
if (array) { return estimates } | |
else { return estimates.slice(-1)[0] } | |
} | |
const f = (x) => { | |
return (Math.pow(x,3))-5 | |
} | |
const df = (x) => { | |
return 3*(Math.pow(x,2)) | |
} | |
console.log(newton(1.5, f, df, 3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment