简体   繁体   中英

Permanently set seed in python

I have read several questions including those aimed specifically at numpy . I am however simply interested in permanently setting seed in(with) random and hence generate the same random float with random.random() with each call. Here's what I did:

import random
random.seed(2) 

First call:

random.random()
0.9560342718892494

Second call:

random.random()
0.9478274870593494

I could keep calling random.seed but would appreciate if someone could explain what is going on or what exactly I can do to set seed once and generate the same random float with each random.random() call.

I am currently trying to learn python so my apologies if this is very basic and already has an answer. I have read several questions before posting.

As pointed out in the comments by @Andrej Kesely and @buzjwa , setting seed does not guarantee that you will get the same value at each call. What is really going on is that we set a random state that then determines the sequence of random floats generated.

When we call random.random() the first time, what we are really doing is initiate the process of random number generation and return the first value in this sequence of numbers.

That is once we set random.seed(2) , each time we follow this with a random.random() call, we return 0.9560342718892494 which is the first value in this sequence of numbers. Subsequent random.random() calls, return the next values in the sequence as per the corresponding call number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM