I want to create a computational rule like, $\frac{\partial}{\partial h_{i}}\int f\left(h_{i}\right)di:=\frac{\partial f\left(h_{i}\right)}{\partial h_{i}}$. This rule is somehow useful when doing models of heterogeneous agents.

To achieve this, I use the code,

D[Integrate[x_, i_], p_] := D[x, p] /; ! FreeQ[p, i]

This works for codes like,

D[Integrate[f[h[i]/p a], i], h[i]]

which returns, $\frac{a f'\left(\frac{a h(i)}{p}\right)}{p}$.

But inexplicably, it does not work for codes like,

D[Integrate[a f[h[i]/p ], i], h[i]]

which returns, $\frac{a \int f'\left(\frac{h(i)}{p}\right) \, di}{p}$ .

The position of a trivial constant "a" does determine whether the rule applies.

I am confused because I think by definition, x_ represents "anything" in mathematica. And !FreeQ[a f[h[i]/p ], i] is obviously True, which means the the rule should apply. What is wrong here?


You're right that a f[h[i]/p matches x_. The problem is that your expression then evaluates to a Integrate[f[h[i]/p ], i], which no longer matches D[Integrate[x_, i_], p_]. You can fix this by instead doing

D[a_. Integrate[x_, i_], p_] := D[a x, p] /; ! FreeQ[p, i]

where we've allowed a_ to take its default value as an argument of Times, which is 1. (See the Optional and Default arguments tutorial for more details.)

Then D[Integrate[a f[h[i]/p], i], h[i]] returns $\frac{a f'\left(\frac{ h(i)}{p}\right)}{p}$, as desired.

Note that you might have to deal with other ways that Integrate evaluates, such as threading over sums. You may wish to avoid this by using something like Inactive[Integrate] (see Inactive) in place of Integrate.

Also note that the usual caveats that come with overloading built in symbols apply. Eventually you could run into trouble from overloading D, particularly if you use somebody else's code which expects D to behave in the default way.

  • $\begingroup$ Thank you so much. That clears all my confusion. $\endgroup$ – diw19 Feb 20 '18 at 8:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.