Your solution was almost correct, except that it should make f
an argument of the hessian function and could implement the derivatives in a more compact way. As pointed out by Mike Honeychurch in the above comments, the first place to start would be to look at the documentation on differentiation.
Here is how the derivative operator D
can be used to define gradients and hessians:
Clear[f, hessian]
Gradient:
D[f[x, y], {{x, y}}]
$\left\{f^{(1,0)}(x,y),f^{(0,1)}(x,y)\right\}$
Hessian (alternative formulation D[f[x,y],{{x,y},2}]
):
D[f[x, y], {{x, y}}, {{x, y}}]
$\left(
\begin{array}{cc}
f^{(2,0)}(x,y) & f^{(1,1)}(x,y) \\
f^{(1,1)}(x,y) & f^{(0,2)}(x,y) \\
\end{array}
\right)$
Now to define the latter as an operator:
hessian[x_, y_] = Function[{f},
D[f, {{x, y}}, {{x, y}}]
];
f[x_, y_] := (x^2 - y)/(x^2 + y^2 + 1);
hessian[x, y][f[x, y]]//FullSimplify
$\left(
\begin{array}{cc}
-\frac{2 \left(3 x^2-y^2-1\right)
\left(y^2+y+1\right)}{\left(x^2+
y^2+1\right)^3} & \frac{2 x
\left((2 y+1) x^2-y (y (2
y+3)+2)+1\right)}{\left(x^2+y^2+
1\right)^3} \\
\frac{2 x \left((2 y+1) x^2-y (y
(2
y+3)+2)+1\right)}{\left(x^2+y^2+
1\right)^3} & -\frac{2
\left(x^4+(1-3 y (y+1))
x^2+y^3-3
y\right)}{\left(x^2+y^2+1\right)
^3} \\
\end{array}
\right)$
To plug in specific values for x
and y
, one approach would be to follow the last result by
%/.{x->2,y->3}
$\left(
\begin{array}{cc}
-\frac{13}{686} & -\frac{29}{343}
\\
-\frac{29}{343} & \frac{53}{686}
\\
\end{array}
\right)$
Here, the %
recalls the result of the previous output, and the /.
stands for ReplaceAll
.
Edit: generalization to n-th derivative
To generalize the Hessian above, you can get the tensor of n
-th derivatives as follows:
D[f[x, y, z], {{x, y, z}, n}]
where n
is the order of the derivative. For example, with n=3
you get
Clear[f];
D[f[x, y, z], {{x, y, z}, 3}] // TableForm
FindMinimum
(local/gradient optimizer, including Newton's method) andNMinimize
(global/derivative-free optimizer). If you really want to code your own implementation (which should not be difficult), see the documentation for the functionD
. This will give you your Jacobian and Hessian directly. $\endgroup$