Contents Previous Next Subchapters

Testing Calculation of The Gradient of a Function
Syntax testgrad(function fvalx0h)
See Also testder , testhess

Given a routine fval that calculates the gradient of a column vector valued function f(x), testgrad compares this calculation with a central difference approximation. (The gradient is the transpose of the derivative.) The results of the comparison are printed in the command window. The column vector x0 specifies the value of x at which to check the calculation of the gradient. The column vector h has the same type and dimension as x0. It specifies the step size to use for each component of x when computing the central difference approximations to the derivative of f(x).

The column vector x1 has the same type and dimension as x0 and specifies a point at which to calculate the value of f(x). The input value of fout does not matter. Its output value is a column vector with the same type as x0 and equal to the value of f(x1). If gout is present, its input value does not matter. Its output value is a matrix with the same type and row dimension as x0. Its column dimension is equal to the row dimension of fout and
               d f (x)  |
                  j     |    
     gout    = -------- |
         i,j   d x      | x = x1
For each component of x, the partials returned by fval, the central difference approximation, and the corresponding relative error are printed in the command window.

The following program checks the gradient calculation for the function f(x) where
            /  x  \     __      |
     f(x) = |     | ,   \/ f(x) |      =  (1, 2)
            \ x^2 /             |x = 1

function fval(x1, fout, gout) begin
     fout = {x1, x1^2}
     if arg(0) == 3 then ...
          gout = [1, 2 * x1]
x0 = 1.
h  = .001
testgrad(function fval, x0, h)