7
$\begingroup$

Consider the following code:

Compile[{{x,_Real}},Module[{x1=x,W},
 W=RandomVariate[NormalDistribution[0, 10^-2], 2];
 x1=x1+W[[1]]+W[[2]];
 x1]]

It fails complaining that W[[1]],W[[2]] is longer that the depth of the variable. How to correctly use a list inside Compile?

$\endgroup$
2
  • $\begingroup$ There is probably no point in "compiling" RandomVariate. The backend of RandomVariate should be compiled already. $\endgroup$ Commented Nov 30, 2021 at 20:13
  • $\begingroup$ @HenrikSchumacher I know, I am sorry. This is just a MWE. $\endgroup$
    – mattiav27
    Commented Dec 1, 2021 at 5:00

1 Answer 1

7
$\begingroup$

Try

cp = Compile[{{x, _Real}}, 
Module[{x1 = x, W = RandomVariate[NormalDistribution[0, 10^-2], 2]}, 
x1 = x1 + W[[1]] + W[[2]];x1]]
$\endgroup$
3
  • $\begingroup$ It works, thanks. But why is my code wrong? It seems the same as yours... $\endgroup$
    – mattiav27
    Commented Nov 30, 2021 at 11:58
  • 1
    $\begingroup$ Probably because Compile has to know the size of W $\endgroup$ Commented Nov 30, 2021 at 12:08
  • 3
    $\begingroup$ Your code works if you change Module to Block ! $\endgroup$ Commented Nov 30, 2021 at 12:13

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.