python随机生成20个数字_python – 生成大量唯一的随机float32数字
最好的辦法是生成隨機(jī)的32位整數(shù),然后將它們轉(zhuǎn)換為浮點(diǎn)數(shù).在生成數(shù)字時(shí),您需要拒絕無窮大和NAN的位表示.
您可以從整數(shù)值而不是浮點(diǎn)值生成集合,然后在輸出上進(jìn)行轉(zhuǎn)換.您可以使用位圖來檢測(cè)已使用的整數(shù)值,而不是使用集合;這更有可能適合內(nèi)存,特別是考慮到你指出的最大樣本量.
def random_unique_floats(n):
used = bytearray(0 for i in xrange(2**32 // 8))
count = 0
while count < n:
bits = random.getrandbits(32)
value = struct.unpack('f', struct.pack('I', bits))[0]
if not math.isinf(value) and not math.isnan(value):
index = bits // 8
mask = 0x01 << (bits & 0x07)
if used[index] & mask == 0:
yield value
used[index] |= mask
count += 1
for num in random_unique_floats(size):
file.write(struct.pack('f', num))
請(qǐng)注意,當(dāng)您的樣本數(shù)接近可能的浮點(diǎn)值數(shù)時(shí),運(yùn)行時(shí)間將呈指數(shù)增長.
總結(jié)
以上是生活随笔為你收集整理的python随机生成20个数字_python – 生成大量唯一的随机float32数字的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: armgcc交叉编译的文件无法运行_认识
- 下一篇: bootstrap .col-md-6