7
$\begingroup$

I'm looking for an elegant way of doing a probability weighted replacement rule,

something like this

f[x_] :=  x /.  {1,2,3,4} -> {50%{ 4,3,2,1} ,50%{1,3,2,4}}

Using an If statement and generating a RandomReal will be very clumsy as I want different probabilities depending on the pattern I want replaced.

Thanks

$\endgroup$
9
$\begingroup$

You can use RandomChoice to randomly select an item from a list.

You can even randomly select an operator and apply it. For example:

f[x_List] := RandomChoice[{Reverse, Identity}][x]

Table[f[{1, 2, 3, 4}], {10}]

returns:

{{4, 3, 2, 1}, {4, 3, 2, 1}, {1, 2, 3, 4}, {1, 2, 3, 4}, {1, 2, 3, 
  4}, {1, 2, 3, 4}, {4, 3, 2, 1}, {1, 2, 3, 4}, {4, 3, 2, 1}, {1, 2, 
  3, 4}}

As pointed by @WReach you can also assign a weight to each choice (weights are automatically normalized, i.e. they not need to sum to 1). For example:

f[x_List] := RandomChoice[{3, 1} -> {Reverse, Identity}][x]
Table[f[{1, 2, 3, 4}], {10}]

returns:

{{4, 3, 2, 1}, {4, 3, 2, 1}, {4, 3, 2, 1}, {4, 3, 2, 1}, {4, 3, 2, 
  1}, {1, 2, 3, 4}, {4, 3, 2, 1}, {1, 2, 3, 4}, {4, 3, 2, 1}, {1, 2, 
  3, 4}}

Your specific pseudo-code can be replaced with something like:

f[x_] := x /. {1, 2, 3, 4} :> RandomChoice[{{1, 2, 3, 4}, {4, 3, 2, 1}}]
Table[f[{1, 2, 3, 4}], {10}]
$\endgroup$
3
$\begingroup$

Another option is to use Condition:

Replace[foo, {foo_ /; RandomReal[] < p :> bar, foo_ :> baz}]

where p is the probability you want to give to the first replacement.

This is somewhat similar to using an If, but I find it somewhat more idiomatic. I would also avoid using ReplaceAll, when you actually want Replace as ReplaceAll might recurse down the whole expression.

You could also explore random function definition:

ff[x_] /; RandomReal[] < p := bar
ff[x_] := baz

Not completely unlike Church

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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