1
$\begingroup$

On the answer of How to impose normalization condition (not initial condition) on DSolve or NDSolve?

k = vars /. sol /. cs[[1]] /. C[_] :> 0 // N;

I see that in the documentation of ReplaceAll and examples of ReplaceAll on the internet, we use Rule (->) instead of RuleDelayed(:>) after ReplaceAll (/.). I don't understand why RuleDelayed has to be used in the above answer.

Using rule:

k = vars /. sol /. cs[[1]] /. C[_] -> 0 // N;

can get the plots I want. But there must be something requiring the use of RuleDelayed in the above answer. What is this? Thank you very much.

$\endgroup$
1
  • 1
    $\begingroup$ As your own testing confirms, you can use either Rule or RuleDelayed in that particular case. $\endgroup$ May 5, 2015 at 20:14

1 Answer 1

5
$\begingroup$

Here is what might be considered a classic example of the difference. Suppose I have a list containing a number of xs and maybe some other elements, and I want to replace the xs with random integers in some range, but I want new random draw for each replacement.

SeedRandom[42]; {x, y, x, x, y} /. x -> RandomInteger[9]
{6, y, 6, 6, y} 

doesn't work because RandomInteger only get called once, before any replacements are made. However,

SeedRandom[42]; {x, y, x, x, y} /. x :> RandomInteger[9]
{6, y, 0, 8, y} 

works just fine because the rule evaluation is delayed and only made when the rule is used. See RuleDelayed

$\endgroup$

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