I am trying to compile a function to speed up execution times.
>From what I have read in the previous posts, the function should return a
numerical value in order to be compileable. I think this condition is met.
Still the compile function does not seem to work:
(*This example calculates the distribution of X = w * M + Z *)
(* Distribution of the stochastic variable M*)
g = PDF[NormalDistribution[0, 1]];
G = CDF[NormalDistribution[0, 1]];
(* Distribution of the stochastic variable Z*)
h = PDF[NormalDistribution[0, 1]];
H = CDF[NormalDistribution[0, 1]];
(* Weight of M in X*)
w = 0.5;
(*Conditional distribution of the stochastic variable X at point x=#1
conditional on M=#2 *)
Qm = Evaluate[H[(#1 - w * #2)/(Sqrt[1 - w^2])]] &
(*Unconditional distribution of the stochastic variable X at point x*)
Q = Integrate[Qm[#1, m]* g[m], {m, -\[Infinity], \[Infinity]}]&
compiledQ = Compile[{x}, Integrate[Qm[x, m]* g[m], {m, -\[Infinity],
\[Infinity]}]]
compiledQ[1]
CompiledFunction::cfse: Compiled expression 1/2 (1+Erf[0.816497 (1.-0.5 m)])
should be a machine-size real number. >>
CompiledFunction::cfex: Could not complete external evaluation at
instruction 2; proceeding with uncompiled evaluation. >>
Comments and tipps are highly welcome :)!
Thank you very much for the advice and best wishes,
Christian
an answer that seems to do the trick is to use NIntegrate instead of
Integrate i.e. compiledQ =
Compile[{x},NIntegrate[Qm[x,m]*g[m],{m,-\[Infinity],\[Infinity]}]].
Also something else that you'd might like to try is to replace the
expression in NIntegrate by
(1 + Erf[((-m)*w + x)/(Sqrt[2]*Sqrt[1 - w^2])])/(E^(m^2/2)*(2*Sqrt[2*Pi]))
which comes from performing the algebra in Qm[x,m]*g[m] (Please check).
The reason that Integrate is slow seems that it attempts to compute the
integral analytically. Why don't you use NIntegrate? You seem to be
interested in numerical result anyway.
In[1] =
Clear[numQ];
numQ[x_?NumericQ] :=
NIntegrate[Qm[x, m]*g[m], {m, -\[Infinity], \[Infinity]}];
In[2] = numQ[0.5] // Timing
Out[2] =
{0.02,0.691462}
I don't think that using Compile will speed up this significantly, in this
particular case,
Regards,
Leonid