Gradient descent: Difference between revisions

→‎{{header|Go}}: Updated solution.
(Added Algol W)
(→‎{{header|Go}}: Updated solution.)
Line 288:
This is a translation of the C# code in the book excerpt linked to above and hence also of the first Typescript example below.
 
However, since it was originally written, I've substituted Fortran's gradient function for the original one (see Talk page) which now gives results which agree (to 6 decimal places) with those of the Fortran, Julia, Algol 68 and Algol W solutions. As a number of other solutions are based on this one, I suggest their authors update them accordingly.
For some unknown reason the results differ from the other solutions after the first 4 decimal places but are near enough for an approximate method such as this.
<lang go>package main
 
Line 302:
 
// Calculate initial gradient.
fi := gradG(x, h)
 
// Calculate initial norm.
Line 321:
 
// Calculate next gradient.
fi = gradG(x, h)
 
// Calculate next norm.
Line 343:
}
 
// Provides a rough calculation of gradient g(xp).
func gradG(xp []float64, h float64) []float64 {
nz := make([]float64, len(xp))
zx := make(p[0]float64, n)
y := make(p[1]float64, n)
z[0] = 2*(x-1)*math.Exp(-y*y) - 4*x*math.Exp(-2*x*x)*y*(y+2)
copy(y, x)
z[1] = -2*(x-1)*(x-1)*y*math.Exp(-y*y) + math.Exp(-2*x*x)*(y+2) + math.Exp(-2*x*x)*y
g0 := g(x)
 
for i := 0; i < n; i++ {
y[i] += h
z[i] = (g(y) - g0) / h
}
return z
}
Line 372 ⟶ 367:
steepestDescent(x, alpha, tolerance)
fmt.Println("Testing steepest descent method:")
fmt.PrintlnPrintf("The minimum is at x[0] =" %f, y = %f for which f(x[0], "y) = %f.\bn", x[10] =", x[1], g(x))
}</lang>
}
</lang>
 
{{out}}
<pre>
Testing steepest descent method:
The minimum is at x[0] = 0.10764302056464771107627, x[1]y = -1.223351901171944223260 for which f(x, y) = -0.750063.
</pre>
 
9,476

edits