Skip to content

Instantly share code, notes, and snippets.

@shinout
Created April 28, 2014 11:43
Show Gist options
  • Save shinout/11369252 to your computer and use it in GitHub Desktop.
Save shinout/11369252 to your computer and use it in GitHub Desktop.
Newton-Raphson method
newton_raphson = (f, x0)->
x0 = Math.random() if typeof x0 isnt "number"
fx0 = f(x0)
x = x0 + 0.01 # for approximating gradient
loop
fx = f(x)
gradient = (fx - fx0) / (x - x0)
delta = fx/gradient
break if Math.abs(delta) < 0.0000001
x0 = x
fx0 = fx
x = x - delta
return x
# sample x^2 + 3x - 2 = 0 : (x-1)(x-2) = 0
console.log newton_raphson (x)->
return Math.pow(x,2) - 3*x + 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment