Skip to content

Instantly share code, notes, and snippets.

@shinout
Created April 28, 2014 15:34
Show Gist options
  • Save shinout/11375620 to your computer and use it in GitHub Desktop.
Save shinout/11375620 to your computer and use it in GitHub Desktop.
steepest descent method
# 最急降下法
steepest = (f, alpha, x0)->
alpha = 1/2 * (Math.abs Math.random()) + 0.1 if typeof alpha isnt "number"
alpha = Math.abs alpha
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 = gradient * (-alpha)
break if Math.abs(delta) < 1e-10
x0 = x
fx0 = fx
x = x + delta
return x
console.log steepest (x)->
return Math.pow(x,2) - 4*x + 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment