Gradient descent: Difference between revisions

→‎{{header|ALGOL 68}}: Use the actual gradient.
(→‎{{header|ALGOL 68}}: Use the actual gradient.)
Line 14:
 
=={{header|ALGOL 68}}==
{{Trans|Go}}
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{Trans|Go}} modified to use the actual gradient function -
There appear to be a range of answers produced by the various samples... the results calculated by this sample differ from the Go sample
{{Trans|GoFORTRAN}}
butTHe results agree with the Fortran sample and the Julia sample to 6 places.
<lang algol68>PROC steepest descent = ( REF[]LONG REAL x, LONG REAL alphap, tolerance )VOID:
BEGIN
LONG REAL alpha := alphap;
LONG REAL h := tolerance;
LONG REAL g0 := g( x ); # Initial estimate of result. #
# Calculate initial gradient. #
[ LWB x : UPB x ]LONG REAL fi := grad g( x, h );
# Calculate initial norm. #
LONG REAL del g := 0.0;
Line 38 ⟶ 37:
x[i] -:= b * fi[i]
OD;
h /:= 2;
# Calculate next gradient. #
fi := grad g( x, h );
# Calculate next norm. #
del g := 0;
Line 47 ⟶ 45:
OD;
del g := long sqrt( del g );
bIF del g > 0 := alpha / del g; THEN
# Calculate next value. #b := alpha / del g;
LONG REAL g1 := g(# xCalculate );next value. #
# Adjust parameter. # LONG REAL g1 := g( x );
IF g1 > g0 THEN# Adjust parameter. #
alphaIF /:=g1 2> g0 THEN
ELSE alpha /:= 2
g0 := g1ELSE
g0 := g1
h /:= 2; FI
FI
OD
END # steepest descent # ;
# calculates the gradient of g(p). #
# Provides a rough calculation of gradient g(x). #
# The derivitives wrt x and y are (as in the Fortran sample ): #
PROC grad g = ( []LONG REAL x, LONG REAL h )[]LONG REAL:
# g' wrt x = 2( x - 1 )e^( - ( y^2 ) ) - 4xe^( -2( x^2) )y( y + 2 ) #
# g' wrt y = ( -2( x-1 )^2ye^( - (y^2) )) + e^(-2( x^2 ) )( y + 2 ) + e^( -2( x^2 ) )y #
PROC grad g = ( []LONG REAL x, LONG REAL hp )[]LONG REAL:
BEGIN
[ LWB xp : UPB xp ]LONG REAL z;
[LONG LWBREAL x := UPBp[ x0 ]LONG REAL y := x;
LONG REAL g0y := g(p[ x1 )];
FORz[ i0 FROM] LWB:= x2 TO* UPB( x DO- 1 ) * long exp( - ( y * y ) )
- 4 * x * long exp( -2 * ( x * x ) ) * y[ i* ]( y +:= h2 );
z[ i1 ] := ( g-2 * ( yx - 1 ) * ( x - g01 ) /* hy ) * long exp( - y * y )
+ long exp( -2 * x * x ) * ( y + 2 )
OD;
+ long exp( -2 * x * x ) * y;
z
END # grad g # ;
# Function for which minimum is to be found. #
# g( x, y ) = ( ( x - 1 )^2 )e^( - ( x^2 ) ) + y( y + 2 )e^( - 2(x^2)) #
PROC g = ( []LONG REAL x )LONG REAL:
( x[ 0 ] - 1 )
3,044

edits