I am investigating Compile lately and I came across the following problem.
I define a 2-variable function
f[x_, y_] :=
If[x < 0 || y < 0, 0,
PDF[PoissonDistribution[3], x]*PDF[PoissonDistribution[2], y]
];
and then I have a new function, which I intend to compile. The non-compiled version of it is:
g[gh_, ga_] :=
Sum[f[i, j], {i, 1 - gh - ga, 10}, {j, 0, i - 1 + gh - ga}];
So when I call for N[g[0, 0] I get 0.584997.
This is my attempt to compile it
gC = Compile[{{gh, _Integer}, {ga, _Integer}},
Sum[f[i, j], {i, 1 - gh - ga, 10}, {j, 0, i - 1 + gh - ga}]
];
and when I call for N[gC[0, 0] I get the very same answer (0.584997) along with the following error.
CompiledFunction::cfex: Could not complete external evaluation at instruction 13; proceeding with uncompiled evaluation. >>
Can anyone understand what am I doing wrong?
Answer
Your function is simple enough that you don't need to rely on pre-defined functions like PDF or PoissonDistribution, just code it all yourself
gC = Compile[{{gh, _Integer}, {ga, _Integer}},
Sum[If[x >= 0 && y >= 0, 3^x/(E^3 x!) 2^y/(E^2 y!), 0], {x,
1 - gh - ga, 10}, {y, 0, x - 1 + gh - ga}]];
gC[0, 0]
(* 0.584997 *)
Edit
As pointed out by J.M., you are safer defining the function as
gC = Compile[{{gh, _Integer}, {ga, _Integer}},
Sum[If[x >= 0 && y >= 0,
Exp[x Log[3] - 3 - LogGamma[x + 1]] Exp[
y Log[2] - 2 - LogGamma[y + 1]], 0], {x, 1 - gh - ga, 10}, {y,
0, x - 1 + gh - ga}]];
which does not give numerical errors for any of the inputs I tested.
Comments
Post a Comment