BlockRandom

BlockRandom[expr]

evaluates expr with all pseudorandom generators localized, so that uses of SeedRandom, RandomInteger, and related functions within the evaluation of expr do not affect subsequent pseudorandom sequences.

Details and Options

  • BlockRandom[expr] in effect saves the states of all pseudorandom generators before evaluating expr, then restores them afterwards.
  • BlockRandom[expr] always gives the same result as just evaluating expr, though it can affect values obtained for subsequent expressions.
  • BlockRandom[expr,RandomSeeding->seeding] specifies that the random generators should be seeded with the specified seeding before evaluating expr.
  • BlockRandom has attribute HoldFirst.
  • Many built-in functions in the Wolfram Language effectively use BlockRandom.

Examples

open allclose all

Basic Examples  (2)

Use BlockRandom to localize the use of a pseudorandom generator:

In[1]:=
Click for copyable input
Out[1]=

Use BlockRandom to prevent one use of a randomized algorithm from affecting others:

In[1]:=
Click for copyable input
Out[1]=
In[2]:=
Click for copyable input
Out[2]=

Scope  (1)

Options  (2)

Applications  (2)

Properties & Relations  (1)

See Also

SeedRandom  RandomSeeding  RandomInteger  RandomReal  RandomChoice  RandomSample  RandomEntity

Tutorials

Introduced in 2007
(6.0)
| Updated in 2017
(11.2)