파이썬에서 0과 1 사이의 난수
이 질문에 이미 답변이 있습니다.
0.3452와 같이 0과 1 사이의 난수를 원합니다. 사용 random.randrange(0, 1)
했지만 항상 0입니다. 어떻게해야합니까?
당신이 사용할 수있는 random.uniform
import random
random.uniform(0, 1)
random.random()
정확히 그렇게
>>> import random
>>> for i in range(10):
... print(random.random())
...
0.908047338626
0.0199900075962
0.904058545833
0.321508119045
0.657086320195
0.714084413092
0.315924955063
0.696965958019
0.93824013683
0.484207425759
정말 난수 를 원하고 [0, 1] 범위를 포함하려면 :
>>> import os
>>> int.from_bytes(os.urandom(8), byteorder="big") / ((1 << 64) - 1)
0.7409674234050893
시도 할 수 있습니다. random.random()
random.random()
[0.0, 1.0) 범위에서 다음 임의의 부동 소수점 숫자를 반환합니다.
에서 https://docs.python.org/2/library/random.html
numpy.random 모듈을 사용할 수 있으며 원하는 모양의 난수 배열을 얻을 수 있습니다.
>>> import numpy as np
>>> np.random.random(1)[0]
0.17425892129128229
>>> np.random.random((3,2))
array([[ 0.7978787 , 0.9784473 ],
[ 0.49214277, 0.06749958],
[ 0.12944254, 0.80929816]])
>>> np.random.random((3,1))
array([[ 0.86725993],
[ 0.36869585],
[ 0.2601249 ]])
>>> np.random.random((4,1))
array([[ 0.87161403],
[ 0.41976921],
[ 0.35714702],
[ 0.31166808]])
>>> np.random.random_sample()
0.47108547995356098
random.randrange (0,2) 작동합니다!
RTM
Python random
모듈에 대한 문서에서 :
Functions for integers:
random.randrange(stop)
random.randrange(start, stop[, step])
Return a randomly selected element from range(start, stop, step).
This is equivalent to choice(range(start, stop, step)), but doesn’t
actually build a range object.
That explains why it only gives you 0, doesn't it. range(0,1)
is [0]
. It is choosing from a list consisting of only that value.
Also from those docs:
random.random()
Return the next random floating point number in the range [0.0, 1.0).
But if your inclusion of the numpy
tag is intentional, you can generate many random floats in that range with one call using a np.random
function.
My variation that I find to be more flexible.
str_Key = ""
str_FullKey = ""
str_CharacterPool = "01234ABCDEFfghij~-)"
for int_I in range(64):
str_Key = random.choice(str_CharacterPool)
str_FullKey = str_FullKey + str_Key
참고URL : https://stackoverflow.com/questions/33359740/random-number-between-0-and-1-in-python
'Programing' 카테고리의 다른 글
ActiveRecord.find (array_of_ids), 순서 유지 (0) | 2020.08.31 |
---|---|
부트 스트랩 날짜 시간 선택기에서 시간 비활성화 (0) | 2020.08.31 |
VS Code에서 "JSON에서 주석이 허용되지 않음"오류를 비활성화합니다. (0) | 2020.08.31 |
Scala에서지도를 반전시키는 우아한 방법 (0) | 2020.08.31 |
매크로가 아직 정의되지 않은 경우에만 정의하는 이유는 무엇입니까? (0) | 2020.08.31 |