Gradient descent: Difference between revisions
→{{header|Wren}}: Replaced existing solution with one based on the updated Go solution.
(→{{header|Go}}: Removed some code which is now superfluous.) |
(→{{header|Wren}}: Replaced existing solution with one based on the updated Go solution.) |
||
Line 1,053:
=={{header|Wren}}==
{{trans|
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "/math" for Math
import "/fmt" for Fmt
// Function for which minimum is to be found.
var
Math.exp(-x[1]*x[1]) + x[1]*(x[1]+2)*
Math.exp(-2*x[0]*x[0])
}
// Provides a rough calculation of gradient
var gradG = Fn.new { |
var
return [2*(x-1)*Math.exp(-y*y) - 4*x*Math.exp(-2*x*x)*y*(y+2),
-2*(x-1)*(x-1)*y*Math.exp(-y*y) + Math.exp(-2*x*x)*(y+2) + Math.exp(-2*x*x)*y]
}
var steepestDescent = Fn.new { |
var
var
// Calculate initial gradient.
▲ var fiy = gra[1]
// Calculate initial norm.
var delG =
for (i in 0...n) delG = delG + fi[i]*fi[i]
delG = delG.sqrt
var b = alpha/delG
// Iterate until value is <= tolerance.
while (delG >
// Calculate next gradient
fix = gra[0]▼
fiy = gra[1]▼
// Calculate next norm.
delG =
for (i in 0...n) delG = delG + fi[i]*fi[i]
b = alpha/delG
// Calculate next value.
// Adjust parameter.
▲ var g1 = f.call(x, y)
if (g1 > g0) {
alpha = alpha / 2
Line 1,102 ⟶ 1,111:
}
}
▲ return [x, y]
}
var tolerance = 0.0000006
var alpha = 0.1
var x = [0.1, -1] // Initial guess of location of minimum.▼
▲// Initial guess of location of minimum.
▲var sd = steepestDescent.call(f, x, y, alpha, tolerance)
System.print("Testing steepest descent method:")
Fmt.print("The minimum is at
{{out}}
<pre>
Testing steepest descent method:
The minimum is at
</pre>
|