Skip to content

Instantly share code, notes, and snippets.

@glmdev
Created October 3, 2018 00:20
Show Gist options
  • Save glmdev/fe84cd6e7fb4fa96ffab1f02108a89aa to your computer and use it in GitHub Desktop.
Save glmdev/fe84cd6e7fb4fa96ffab1f02108a89aa to your computer and use it in GitHub Desktop.
A Javascript function to run a Newton's Method sequence
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