2
$\begingroup$

I have a rather basic question but can't figure out a foolproof answer. In the following code, I build a function which returns the mean difference between successive elements of a vector created from j random variates from an exponential distribution:

fun2[j_] := 
    Module[{x = RandomVariate[ExponentialDistribution[1/25], j]}, 
    Mean[Table[Abs[x[[i + 1]] - x[[i]]], {i, Length[x] - 1}]]]

Will the use of the x call to RandomVariate create an immutable object, i.e. so that x[[i + 1]] and x[[i]] reference the same instance of the distribution?

Thanks a lot for any help.

$\endgroup$
1
  • $\begingroup$ Any reason you are avoiding Mean[Abs@Differences[x]]? That seems a lot simpler here. Not to mention, it will be much faster. $\endgroup$
    – Andy Ross
    May 19, 2014 at 12:47

1 Answer 1

2
$\begingroup$

Yes. Notice that performing the computation outside of the Module produces the same result.

SeedRandom[1];
fun2[10]

(* 30.5828 *)

SeedRandom[1];
x = RandomVariate[ExponentialDistribution[1/25], 10];
Mean[Abs[Differences[x]]]

(* 30.5828 *)

In order to get the undesired behavior you would use SetDelayed as such..

fun3[j_] := 
 Module[{x := RandomVariate[ExponentialDistribution[1/25], j]}, 
  Mean[Table[Abs[x[[i + 1]] - x[[i]]], {i, Length[x] - 1}]]]

This gives a totally different result.

SeedRandom[1];
fun3[10]

(* 34.018 *)
$\endgroup$

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.