7
$\begingroup$

Is there a way to fix SeedRandom[.] for an entire notebook? If I carry out many calculations using random numbers, I need to give a separate code SeedRandom[45], for example, for each cell in the notebook. This is inefficient for calculations done in many different cells because I need to indicate the same seed for each cell.

How can I set SeedRandom[.] once for all random number-based computations done in various cells in a notebook?

$\endgroup$
8
  • 1
    $\begingroup$ The objective doesn't seem well defined. SeedRandom sets the initial seed, but we don't know how many "fetches" you need between re-seedings. There could be multiple calculations in one given cell that need a random value. And some other cell might not need any randomness. One possible interpretation of your objective would be that after every single random value generation, the seed is reset back to 45. But, as @MarcoB pointed out, that would eliminate the randomness, so that can't be what you're asking for. But I can't think of an alternate interpretation. $\endgroup$
    – lericr
    Jan 22 at 21:54
  • 2
    $\begingroup$ I think OP is clear what he wants - each cell should be evaluated with SeedRandom[45] before evaluation of the code of the cell. $\endgroup$ Jan 22 at 23:00
  • 1
    $\begingroup$ try also evaluating $PreRead = (SeedRandom[45]; #) &; before other cells in the notebook. $\endgroup$
    – kglr
    Jan 22 at 23:03
  • 2
    $\begingroup$ @kglr: If I am not mistaken $PreRead will be applied to each line (expression) of the cell, not only once at the beginning of the cell. $\endgroup$ Jan 22 at 23:05
  • 2
    $\begingroup$ @azerbajdzan, you are right. $\endgroup$
    – kglr
    Jan 22 at 23:09

1 Answer 1

9
$\begingroup$
SetOptions[EvaluationNotebook[], CellProlog :> (SeedRandom[45])]

Then before evaluating any cell SeedRandom[45] is evaluated.

RandomInteger[10]
RandomInteger[10]
RandomInteger[10]
RandomInteger[10]

9

4

9

0

Next cell gives the same output:

RandomInteger[10]
RandomInteger[10]
RandomInteger[10]
RandomInteger[10]

9

4

9

0

To cancel CellProlog evaluate:

SetOptions[EvaluationNotebook[], CellProlog :> (None)]
$\endgroup$

Your Answer

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

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