2
$\begingroup$

This question is aimed at improving both my coding and my understanding of MMa's capabilities. A lot of my code is still hacks and workarounds for things I don't know how to do properly.

I want to calculate the gradient and Hessian of:

$$z[a_{1},...,a_{n}]\equiv\int_{-\infty}^{\infty}e^{f[x,a_{1},...,a_{n}]}dx$$

where $f[x,a_{1},...,a_{n}]\equiv\sum_{i}a_{i}\left(x^{i}-m_{i}\right)$ and the $m_{i}$'s are just constants. All variables and constants are Real. The hard part is, I want to express the gradient and Hessian in terms of:

$$c_{j}\equiv\int_{-\infty}^{\infty}x^{j}e^{f[x,a_{1},...,a_{n}]}dx$$

(Note that $c_{0}=z[a_{1},...,a_{n}]$).

So here is my code for the gradient:

ord = 4;
p[x_] := Exp[Sum[a[i]*(x^i - m[i]), {i, 0, ord}]];
aa = Table[a[i], {i, 0, ord}];

temp1 = D[p[x], {aa}]/p[x];
temp2 = temp1 /. x -> 0;
grad = temp2*c[0] + (temp1 - temp2) /. x^q_ -> c[q] /. x -> c[1] // Expand

(* {c[0] - c[0] m[0], c[1] - c[0] m[1], c[2] - c[0] m[2], c[3] - c[0] m[3], c[4] - c[0] m[4]} *)

Basically, I am dividing out the exponential and doing substitutions directly on the integrand in order to avoid using Integrate[], because I don't know how to use patterns to substitute unsolved integrals. In the last two lines, I have to do the substitutions on $c_0,c_{j>1},c_1$ in three separate respective steps because the pattern x_r doesn't work for $r=0,1$.

I use the same basic method for the Hessian:

temp3 = D[p[x], {aa, 2}]/p[x] // Expand;
temp4 = temp3 /. x -> 0;
hess = temp4*c[0] + (temp3 - temp4) /. x^q_ -> c[q] /. x -> c[1] // Expand;

Could this be done better? Or are there some things we can only do with MMa using hacks like this?

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.