Created
April 28, 2014 11:43
-
-
Save shinout/11369252 to your computer and use it in GitHub Desktop.
Newton-Raphson 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_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