1
$\begingroup$

I have observed something strange happening with the function ND[] from the package NumericalCalculus. In particular, if I define a function G that returns the numerical derivative of a compiled function f, like

f = Compile[{{x, _Real}}, x^2];
<< NumericalCalculus`
G[a_] := Module[{g},  g[x_?NumericQ] := f[x]; ND[g[x], x, a]];

and I try to use this function inside a ParallelTable[] or a Table[], like

ParallelTable[G[x], {x, 0.0, 10.0, 1.0}]
(* output: {1.`,1.`,0.`,0.`,0.`,0.`,0.`,0.`,0.`,0.`,0.`} *)
Table[G[x], {x, 0.0, 10.0, 1.0}]
(* output {1.`,1.`,0.`,0.`,0.`,0.`,0.`,0.`,0.`,0.`,0.`} *)
Map[G[#] &,  Table[x, {x, 0.0, 10.0, 1.0}]]
(* output {0.`,2.`,4.`,6.`,8.`,10.`,12.`,14.`,16.`,18.`,20.`} *)
ParallelMap[G[#] &,  Table[x, {x, 0.0, 10.0, 1.0}]]
(* output {0.`,2.`,4.`,6.`,8.`,10.`,12.`,14.`,16.`,18.`,20.`} *)

I get wrong results (as compared to the use of Map[] or ParallelMap[] that give the predicted numbers). Can you help me with this? I have Mathematica 14.1

$\endgroup$
1
  • $\begingroup$ Too many x's. Try Table[G[a], {a, 0, 10, 1}] $\endgroup$
    – Bill Watts
    Commented Oct 21 at 23:27

1 Answer 1

2
$\begingroup$

The first problem is "ND" needs a symbol as variable, not a real number. If g[x_?NumericQ] := f[x] evaluates, x is a real number. Therefore,you need to replace ND[g[x], x, a] by ND[g[y], y, a].

The second problem is that g, as a local variable, is not distributed to parallel kernels. Make g global to ensure that it is distriuted.

f = Compile[{{x, _Real}}, x^2];
<< NumericalCalculus`
G[a_] := Module[{}, g[x_?NumericQ] := f[x]; ND[g[y], y, a]];

ParallelTable[G[x], {x, 0.0, 10.0, 1.0}]
Table[G[x], {x, 0.0, 10.0, 1.0}]
Map[G[#] &, Table[x, {x, 0.0, 10.0, 1.0}]]
ParallelMap[G[#] &, Table[x, {x, 0.0, 10.0, 1.0}]]

enter image description here

$\endgroup$
2
  • $\begingroup$ Didn't try it, but I'd also expect to need a ParallelNeeds["NumericalCalculus`"], to make sure that the calculation is actually done on the subkernels. $\endgroup$
    – Szabolcs
    Commented Oct 22 at 9:39
  • $\begingroup$ With ParallelNeeds this works! Thanks :) $\endgroup$
    – Matteo
    Commented Oct 22 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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