Using Python's random.seed()

Hi, I’m used to count on random.seed() to set a fixed starting point for further random.choice() and random.randin() calls on my generative projects in Python, but, maybe because I’m not used to web deployment and flask, I’m not getting the behavior I expected (probably my mental model of code execution sequence is broken).

Can someone help me with an insight?


https://holy-season-roquefort.glitch.me/?colunas=8&seed=1&sf=10

I expected random.seed() to work inside draw() but it doesn’t (does not produce always the same drawing with the same seed)

Now I kind of can get the same drawing fixing the seed inside ensemble() but this is not what I wanted (and like this I can’t produce the same drawing on different scales)

Following the trail of function calls …

  1. draw sets random.seed
  2. draw calls grid
  3. grid calls ensamble
  4. ensamble sets random.seed with a different value than was set by draw
    i.e. the seed set in draw is overridden before it is used.
  5. ensamble uses some random numbers/choices

Edit - also note that ensamble sets the random seed based on two of its parameters, ex, ey. If the third parameter eo is different, a different number of random calls are made, so you will get variation from expected, after a number of times through the loop. You’d likely get what you want by including eo in the seed value calculation.

2 Likes

Hi @mishavee, thank you for you time and attention!

To clarify, the setting of random.seed inside ensemble is a dirty workaround, I don’t want it.
I would like to understand why setting it inside draw only doesn’t work.
I’m going to comment out the workaround so you can see the issue.

  1. draw() sets seed with value 1
  2. draw() calls grid() with ensemble on arguments
  3. grid() function repeteadly calls ensamble() function
  4. ensamble() function executes some random.randint() and random.choice()

Each time the app is refreshed it should call draw, that should set the same seed… and produce the same drawing… but it doesn’t. Each refresh generates a different drawing.

Thanks again!

This might be a rather useless reply, but if you put a randomizing function like randint() inside of a function, and then call the function repeatedly, then the random number would change. If you wanted one random number that’s constant, put randint() outside of the function and use the variable inside the function.

1 Like

Hi @CarlyRaeJepsenStan!

It is rather common when working with generative art to call random() several times but to kind of freeze all of those results with a single seed setting at the beginning of the job. This way one can reproduce the output for a certain seed (when it is raster work, to produce a high-resolution output of chosen low-res previews of certain seeds, for instance).

1 Like

For some reason I don’t understand at all, it looks like it is working now…