Many built-in functions throw errors before executing a ReplaceAll. The functions still execute the ReplaceAll as intended, but the spurious errors are a nuisance. I can avoid this problem using ReleaseHold and Hold, but there's probably a better way.

Here's one of many examples:

RandomVariate[NormalDistribution[20, 10]]
(* 5.2037 *)

RandomVariate[NormalDistribution[μ, σ]] /. {μ -> 20, σ -> 10}
(* During evaluation of In[67]:= RandomVariate::posprm: Parameter σ 
   at position 2 in NormalDistribution[μ,σ] is expected to be positive. *)
(* 6.78478 *)

ReleaseHold[Hold[RandomVariate[NormalDistribution[μ, σ]]] /. {μ -> 20, σ -> 10}]
(* 46.4181 *)
  • 2
    $\begingroup$ Just Quiet should do the trick. But, I have two questions. Firstly, how do you know that you will always have the values of mu and sigma handy when the error message is thrown? Secondly, if you intend to invoke RandomVariate only after you have computed the values of mu and sigma, why not do something like {20, 10} // Apply[NormalDistribution /* RandomVariate]? In other words, why not first assemble all the atomic values that you need and then apply the appropriate heads? $\endgroup$ Jan 12 at 1:24
  • 2
    $\begingroup$ You could also wrap the relevant code in a With, Block, or Module containing the appropriate definition for mu and sigma. $\endgroup$
    – MarcoB
    Jan 12 at 3:03
  • $\begingroup$ You may force MMA to do the replacement by: RandomVariate[ Evaluate[ NormalDistribution[\[Mu], \[Sigma]]] /. {\[Mu] -> 20, \[Sigma] -> 10}] $\endgroup$ Jan 12 at 7:59
  • 1
    $\begingroup$ It is the evaluation order of Mathematica that is in your way; you can read a lot about it in the tech note on Evaluation Control. There are multiple ways to do this, as already mentioned by others in the comments, for example, for your case, you could also use Unevaluated: Unevaluated@RandomVariate[NormalDistribution[μ, σ]] /. {μ -> 20, σ -> 10}. $\endgroup$
    – Domen
    Jan 12 at 13:45
  • $\begingroup$ The Quiet[] idea has the problem of silencing desired errors. The others (With, Block, Module, Apply and Unevaluated) are all good, simple solutions. Thanks, MarcoB, Daniel Huber, Shredderroy and Domen. $\endgroup$
    – crabtree
    Jan 12 at 15:35


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.