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|zklGo}}
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
Slightly different result but close enough.
<lang ecmascript>import "/math" for Math
import "/fmt" for Fmt
 
// Function for which minimum is to be found.
var fg = Fn.new { |x, y| (x-1)*(x-1)*Math.exp(-y*y) + y*(y+2)*Math.exp(-2*x*x) }
return (x[0]-1)*(x, y[0]-1)*
Math.exp(-x[1]*x[1]) + x[1]*(x[1]+2)*
Math.exp(-2*x[0]*x[0])
}
 
// Provides a rough calculation of gradient fg(x, yp).
var gradG = Fn.new { |f, x, y, hp|
var g0x = f.call(x, y)p[0]
var fiyy = grap[1]
return [(f.call(x + h, y) - g0) / h, (f.call(x, y + h) - g0) / h]
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 { |f, x, y, alpha, htolerance|
var g0n = f.call(x, y) // Initial estimate of result.count
var grag0 = gradGg.call(f, x, y, h) // Calculate// Initial estimate initialof gradientresult.
 
var fix = gra[0]
// Calculate initial gradient.
var fiy = gra[1]
var g1fi = fgradG.call(x, y)
 
// Calculate initial norm.
var delG = (fix*fix + fiy*fiy).sqrt0
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 > htolerance) {
x// =Calculate xnext - b*fixvalue.
yfor (i in 0...n) x[i] = yx[i] - b*fiyfi[i]
 
// Calculate next gradient and next value.
hfi = h / 2gradG.call(x)
gra = gradG.call(f, x, y, h)
fix = gra[0]
fiy = gra[1]
 
// Calculate next norm.
delG = (fix*fix + fiy*fiy).sqrt0
for (i in 0...n) delG = delG + fi[i]*fi[i]
fixdelG = gra[0]delG.sqrt
b = alpha/delG
 
// Calculate next value.
fiyvar g1 = gra[1]g.call(x)
 
// 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.
 
var sd = steepestDescent.call(f, x, y, alpha, tolerance)
// Initial guess of location of minimum.
var x = 0.1
var y = -1
var sd = steepestDescent.call(f, x, y, alpha, tolerance)
x = sd[0]
y = sd[1]
System.print("Testing steepest descent method:")
Fmt.print("The minimum is at (x, y) = ($f, y = $f). for which f(x, y) = $f.", x[0], yx[1], fg.call(x, y))</lang>
 
{{out}}
<pre>
Testing steepest descent method:
The minimum is at (x, y) = (0.107612107627, y = -1.223291).223260 for which f(x, y) = -0.750063.
</pre>
 
9,479

edits