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}}
<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
p[1] = 2*(x-1)*exp(-y*y) - 4*x*exp(-2*x*x)*y*(y+2)
p[2] = -2*(x-1)*(x-1)*y*exp(-y*y) + exp(-2*x*x)*(y+2) + exp(-2*x*x)*y
end function
function steepestDescent(sequence x, atom alpha, tolerance)
integer n = length(x)
atom
-- Calculate initial gradient.
sequence fi = gradG(x
-- 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))
-- Calculate next gradient.
fi = gradG(x
-- 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
{{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
</pre>
|