Gradient descent: Difference between revisions

m
→‎{{header|Phix}}: applied the Go updates
(→‎{{header|Wren}}: Replaced existing solution with one based on the updated Go solution.)
m (→‎{{header|Phix}}: applied the Go updates)
Line 463:
=={{header|Phix}}==
{{trans|Go}}
... and just like Go, the results don't quite match anything else.
<lang Phix>-- Function for which minimum is to be found.
function g(sequence x)
Line 472 ⟶ 471:
 
-- Provides a rough calculation of gradient g(x).
function gradG(sequence x, atom hp)
integeratom n{x,y} = length(x)p
p[1] = 2*(x-1)*exp(-y*y) - 4*x*exp(-2*x*x)*y*(y+2)
sequence z = repeat(0, n)
p[2] = -2*(x-1)*(x-1)*y*exp(-y*y) + exp(-2*x*x)*(y+2) + exp(-2*x*x)*y
atom g0 := g(x)
forreturn i=1 to n dop
x[i] += h
z[i] = (g(x) - g0) / h
end for
return z
end function
 
function steepestDescent(sequence x, atom alpha, tolerance)
integer n = length(x)
atom hg0 = tolerance,g(x) -- Initial estimate of result.
g0 = g(x) -- Initial estimate of result.
 
-- Calculate initial gradient.
sequence fi = gradG(x, h)
 
-- Calculate initial norm.
atom delG = sqrt(sum(sq_mul(fi,fi))),
b = alpha / delG
 
-- Iterate until value is <= tolerance.
while delG>tolerance do
-- Calculate next value.
x = sq_sub(x,sq_mul(b,fi))
h /= 2
-- Calculate next gradient.
fi = gradG(x, h)
-- Calculate next norm.
Line 524 ⟶ 517:
sequence x = steepestDescent({0.1,-1}, alpha, tolerance)
printf(1,"Testing steepest descent method:\n")
printf(1,"The minimum is at x[1] = %.16f13f, y = %.13f for which f(x[1], y) = %.16f\n", {x[1], x[2], g(x)})</lang>
{{out}}
Results now match (at least) Go, Fortran, Julia, and Wren [to >=6dp]. Results on 32/64 bit agree to 13dp, which I therefore choose to show in full here.
<pre>
Testing steepest descent method:
The minimum is at x[1] = 0.10765720809349961076268243295, x[1]y = -1.22329760804758902232596548816 for --which f(64x, bity) = -0.7500634205514924
The minimum is at x[1] = 0.1073980565405569, x[1] = -1.2233251778997771 -- (32 bit)
</pre>
 
7,813

edits