Programing

random.seed () : 무엇을합니까?

lottogame 2020. 6. 5. 08:01
반응형

random.seed () : 무엇을합니까?


random.seed()파이썬 에서하는 일에 약간 혼란 스럽습니다 . 예를 들어, 아래 시험이 왜 (일관되게) 수행합니까?

>>> import random
>>> random.seed(9001)
>>> random.randint(1, 10)
1
>>> random.randint(1, 10)
3
>>> random.randint(1, 10)
6
>>> random.randint(1, 10)
6
>>> random.randint(1, 10)
7

이것에 대한 좋은 문서를 찾을 수 없었습니다.


의사 난수 생성기는 값에 대해 일부 작업을 수행하여 작동합니다. 일반적으로이 값은 생성기에 의해 생성 된 이전 숫자입니다. 그러나 생성기를 처음 사용할 때는 이전 값이 없습니다.

의사 난수 생성기를 시드하면 첫 번째 "이전"값이 제공됩니다. 각 시드 값은 주어진 난수 생성기에 대해 생성 된 일련의 값에 해당합니다. 즉, 동일한 시드를 두 번 제공하면 동일한 숫자의 시퀀스가 ​​두 번 나타납니다.

일반적으로 난수 생성기를 프로그램의 각 실행을 변경하는 값으로 시드하려고합니다. 예를 들어, 현재 시간은 자주 사용되는 시드입니다. 이것이 자동으로 발생하지 않는 이유는 원하는 경우 알려진 시드 시퀀스를 얻기 위해 특정 시드를 제공 할 수 있기 때문입니다.


다른 모든 답변은 random.seed () 사용을 설명하지 않는 것 같습니다. 다음은 간단한 예입니다 ( source ).

import random
random.seed( 3 )
print "Random number with seed 3 : ", random.random() #will generate a random number 
#if you want to use the same random number once again in your program
random.seed( 3 )
random.random()   # same random number as before

>>> random.seed(9001)   
>>> random.randint(1, 10)  
1     
>>> random.seed(9001)     
>>> random.randint(1, 10)    
1           
>>> random.seed(9001)          
>>> random.randint(1, 10)                 
1                  
>>> random.seed(9001)         
>>> random.randint(1, 10)          
1     
>>> random.seed(9002)                
>>> random.randint(1, 10)             
3

당신은 이것을 시도하십시오. 'random.seed'는이 시드를 기준으로 이러한 값을 생성하는 임의 값 생성기 ( 'random.randint ()')에 값을 제공한다고 가정합니다. 난수의 필수 속성 중 하나는 재현 할 수 있어야한다는 것입니다. 동일한 시드를 넣으면 동일한 패턴의 난수를 얻습니다. 그래서 당신은 처음부터 다시 생성하고 있습니다. 다른 초기 값으로 시작하는 다른 시드를 제공합니다 (3 개 이상).

시드를 주면 1에서 10 사이의 난수가 차례로 생성됩니다. 따라서 하나의 시드 값에 대해 하나의 숫자 세트를 가정 할 수 있습니다.


난수는 이전 값에 약간의 조작에 의해 발생된다.

이전 값이 없으면 현재 시간이 이전 값으로 자동 설정됩니다. 우리는 사용 자체에 의해이 이전 값을 제공 할 수있는 random.seed(x)경우 x임의의 숫자 나 문자열 등이 될 수

따라서 random.random()실제로 완벽한 난수는 아니지만를 통해 예측할 수 있습니다 random.seed(x).

import random 
random.seed(45)            #seed=45  
random.random()            #1st rand value=0.2718754143840908
0.2718754143840908  
random.random()            #2nd rand value=0.48802820785090784
0.48802820785090784  
random.seed(45)            # again reasign seed=45  
random.random()
0.2718754143840908         #matching with 1st rand value  
random.random()
0.48802820785090784        #matching with 2nd rand value

따라서 난수 생성은 알고리즘에서 실행되므로 실제로 난수가 아닙니다. 알고리즘은 항상 동일한 입력을 기반으로 동일한 출력을 제공합니다. 이것은 종자의 가치에 달려 있음을 의미합니다. 따라서 더 무작위로 만들기 위해 시간이 자동으로에 할당됩니다 seed().


Seed() can be used for later use ---

Example:
>>> import numpy as np
>>> np.random.seed(12)
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>
>>>
>>> np.random.seed(12) # When you use same seed as before you will get same random output as before
>>> np.random.rand(4)
array([0.15416284, 0.7400497 , 0.26331502, 0.53373939])
>>>
>>>
>>> np.random.seed(10)
>>> np.random.rand(4)
array([0.77132064, 0.02075195, 0.63364823, 0.74880388])
>>>

# Simple Python program to understand random.seed() importance

import random

random.seed(10)

for i in range(5):    
    print(random.randint(1, 100))

위의 프로그램을 여러 번 실행하십시오 ...

첫 번째 시도 : 1-100 범위에서 5 개의 임의의 정수를 인쇄합니다

두 번째 시도 : 위의 실행에서 동일한 5 개의 난수를 인쇄합니다.

세 번째 시도 : 동일

.....곧

Explanation: Every time we are running the above program we are setting seed to 10, then random generator takes this as a reference variable. And then by doing some predefined formula, it generates a random number.

Hence setting seed to 10 in the next execution again sets reference number to 10 and again the same behavior starts...

As soon as we reset the seed value it gives the same plants.

Note: Change the seed value and run the program, you'll see a different random sequence than the previous one.


In this case, random is actually pseudo-random. Given a seed, it will generate numbers with an equal distribution. But with the same seed, it will generate the same number sequence every time. If you want it to change, you'll have to change your seed. A lot of people like to generate a seed based on the current time or something.


Imho, it is used to generate same random course result when you use random.seed(samedigit) again.

In [47]: random.randint(7,10)

Out[47]: 9


In [48]: random.randint(7,10)

Out[48]: 9


In [49]: random.randint(7,10)

Out[49]: 7


In [50]: random.randint(7,10)

Out[50]: 10


In [51]: random.seed(5)


In [52]: random.randint(7,10)

Out[52]: 9


In [53]: random.seed(5)


In [54]: random.randint(7,10)

Out[54]: 9

Here is a small test that demonstrates that feeding the seed() method with the same argument will cause the same pseudo-random result:

# testing random.seed()

import random

def equalityCheck(l):
    state=None
    x=l[0]
    for i in l:
        if i!=x:
            state=False
            break
        else:
            state=True
    return state


l=[]

for i in range(1000):
    random.seed(10)
    l.append(random.random())

print "All elements in l are equal?",equalityCheck(l)

Set the seed(x) before generating a set of random numbers and use the same seed to generate the same set of random numbers. Useful in case of reproducing the issues.

>>> from random import *
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>> 

Here is my understanding. Every time we set a seed value, a "label" or " reference" is generated. The next random.function call is attached to this "label", so next time you call the same seed value and random.function, it will give you the same result.

np.random.seed( 3 )
print(np.random.randn()) # output: 1.7886284734303186

np.random.seed( 3 )
print(np.random.rand()) # different function. output: 0.5507979025745755

np.random.seed( 5 )
print(np.random.rand()) # different seed value. output: 0.22199317108973948

참고URL : https://stackoverflow.com/questions/22639587/random-seed-what-does-it-do

반응형