I've been using the code below to efficiently sample from multivariate Gaussian with diagonal covariance matrix. Now I want to try the same for Cauchy samples, however replacing NormalDistribution
with CauchyDistribution
fails with CompiledFunction::cfse: Compiled expression {{1.54755,-2.73921},{1.28524,-1.49352}} should be a machine-size real number.
I suspect CauchyDistribution
is not supported by compile. Is there a workaround?
Compilation speeds up multivariate Gaussian sampling by an order of magnitude. (related post)
gaussianSampler[mu_, diag_] :=
With[{d = Length[diag]}, Assert[d > 0];
Compile[{{n, _Integer}},
Module[{vals},
vals =
mu + Sqrt[diag]*# & /@
RandomVariate[NormalDistribution[], {Max[n, 1], d}]]]];
sampler = gaussianSampler[{0, 0}, {1, 2}];
sampler[5]
RandomVariate[ MultinormalDistribution[\[Mu], DiagonalMatrix[diag]], {n, d}]
? It seems to be at least twice as fast assampler
. $\endgroup$ConstantArray[mu, n] + RandomVariate[NormalDistribution[], {n, d}] . DiagonalMatrix[diag]
would have the same effect. $\endgroup$ConstantArray[mu, n] + RandomVariate[CauchyDistribution[0., 1.], {n, d}].DiagonalMatrix[diag]
does what you want? $\endgroup$CauchyDistribution
not being compileable: $$ $$ If $u$ is a uniform r.v. on [0,1], you can get a r.v. $x$ distributed as the standard Cauchy distribution by the transform: ${\displaystyle x=\tan \left(\pi (u-{\frac {1}{2}})\right)}$ $\endgroup$