TransWikia.com

Differentiate a numerically defined function

Mathematica Asked by potatosoup on January 25, 2021

My function is

f[a_, b_] := NIntegrate[Sqrt[(Cos[t] - a)^2 + b^2], {t, 0, Pi}]

I want to calculate g[1,1] where g[a,b] is defined as…

g[a_, b_] := Derivative [1, 0][f][a, b]

I get the error

The integrand has evaluated for non-numerical values…

Now I can easily calculate the derivative first and not get an error, but I don’t want to do that for a particular reason. I can also use a finite difference formula that I create myself, but I want to use procedures already defined by Mathematica.

Is it possible to avoid this error and calculate the derivative of a numerical integral?

4 Answers

This should work:

Clear[f];
f[a_?NumericQ, b_?NumericQ] := NIntegrate[Sqrt[(Cos[t] - a)^2 + b^2], {t, 0, Pi}]

and then add //N at the end of the definition of g[a,b]

g[a_, b_] := Derivative[1, 0][f][a, b]//N
g[1,1]
(*1.80525*)

Answered by Nikolay Gromov on January 25, 2021

Just ignore the error message. Use

g[a_, b_] := Quiet@Derivative[1, 0][f][a, b]
(* 1.80525 *)

This answer can be verified by

(f[1.005, 1] - f[.995, 1])/.01
(* 1.80525 *)

Answered by bbgodfrey on January 25, 2021

If the function can be evaluated at complex arguments, one possibility is to use the complex step derivative approximation of Squire and Trapp.

For this function, it proceeds like so:

f[a_?NumericQ, b_?NumericQ] := NIntegrate[Sqrt[(a - Cos[t])^2 + b^2], {t, 0, Pi}]

(* complex step approximation *)
With[{x = 1, y = 1, h = $MachineEpsilon}, Im[f[x + I h, y]]/h]
   1.80525

(* analytic derivative *)
With[{a = 1, b = 1},
     NIntegrate[(a - Cos[t])/Sqrt[(a - Cos[t])^2 + b^2], {t, 0, Pi}]]
   1.8052526175436538

Answered by J. M.'s ennui on January 25, 2021

Here's a variation of bbgodfrey's answer that doesn't require quieting:

g[a_,b_]:=Activate @ Block[{NIntegrate=Inactive[NIntegrate]},Derivative[1,0][f][a,b]]

Check:

g[1, 1]

1.80525

The trick is that Mathematica knows how to take derivatives of inactive integrals, so temporarily inactivating NIntegrate avoids having NIntegrate trying to integrate a symbolic integrand.

Answered by Carl Woll on January 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP