Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
    
Any reason you are avoiding Mean[Abs@Differences[x]]? That seems a lot simpler here. Not to mention, it will be much faster. –  Andy Ross May 19 at 12:47

1 Answer 1

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 *)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.