0
$\begingroup$

I need to numerically differentiate a function that takes a list as an argument and that uses NIntegrate in its definition. A simple example is

Needs["NumericalCalculus`"]

f[x_] := NIntegrate[Cos[(x[[1]] + x[[2]]) y], {y, 0, 1}];
ND[f[{1, 0} x], x, 1]

which returns the non-numerical value warning. I tried

f[x_?NUmericQ] := NIntegrate[Cos[(x[[1]] + x[[2]]) y], {y, 0, 1}];

but this does not evaluate either. Any ideas?

EDIT IN RESPONSE TO ANSWER

What if f is redefined as

f[x_, u_] := NIntegrate[Cos[(x[[1]] + x[[2]] + u) y], {y, 0, 1}];

where u is a scalar and we wish to evaluate expressions like

ND[f[{1, 0} x, 3], x, 1]

and

ND[f[{1, 1}, u], u, 1]

I tried:

f[x_, u_] /; VectorQ[x, NumericQ] && NumericQ[u] :=
NIntegrate[Cos[(x[[1]] + x[[2]] + u) y], {y, 0, 1}]
$\endgroup$
  • $\begingroup$ Could you check your new examples for correctness? In principle it seems to me that you should be able to define f[x_?(VectorQ[#, NumericQ]&), u?NumericQ] := ... if you want $x$ to be a vector of numerical quantities, and $u$ a numerical scalar. But then if everything is numerical, f will simply return a scalar, so what should ND do with that then? $\endgroup$ – MarcoB Mar 22 '16 at 6:07
  • $\begingroup$ @MarcoB your suggestion does the job. Cheers... $\endgroup$ – Freakalien Mar 22 '16 at 9:06
2
$\begingroup$

Define it instead as

f[x_] /; VectorQ[x, NumericQ] := NIntegrate[Cos[(x[[1]] + x[[2]]) y], {y, 0, 1}]

so that it only explicitly works on a list of numerical values.

$\endgroup$
  • $\begingroup$ I am unfamiliar with this approach. To get a better understanding I have extended my original question to cover the case where the function f takes both a list and a scalar as arguments. What can be done in this case? $\endgroup$ – Freakalien Mar 22 '16 at 4:20

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.