Christian
Christian

Reputation: 26427

Seeding random in django

In a view in django I use random.random(). How often do I have to call random.seed()? One time for every request? One time for every season? One time while the webserver is running?

Upvotes: 4

Views: 2840

Answers (3)

Paul Tarjan
Paul Tarjan

Reputation: 50642

Don't set the seed.

The only time you want to set the seed is if you want to make sure that the same events keep happening. For example, if you don't want to let players cheat in your game you can save the seed, and then set it when they load their game. Then no matter how many times they save + reload, it still gives the same outcomes.

Upvotes: 4

S.Lott
S.Lott

Reputation: 391952

Call random.seed() rarely if at all.

To be random, you must allow the random number generator to run without touching the seed. The sequence of numbers is what's random. If you change the seed, you start a new sequence. The seed values may not be very random, leading to problems.

Depending on how many numbers you need, you can consider resetting the seed from /dev/random periodically.

You should try to reset the seed just before you've used up the previous seed. You don't get the full 32 bits of randomness, so you might want to reset the seed after generating 2**28 numbers.

Upvotes: 3

a_m0d
a_m0d

Reputation: 12205

It really depends on what you need the random number for. Use some experimentation to find out if it makes any difference. You should also consider that there is actually a pattern to pseudo-random numbers. Does it make a difference to you if someone can possible guess the next random number? If not, seed it once at the start of a session or when the server first starts up.

Seeding once at the start of the session would probably make the most sense, IMO. This way the user will get a set of pseudo-random numbers throughout their session. If you seed every time a page is served, they aren't guaranteed this.

Upvotes: 0

Related Questions