簡體   English   中英

如何從[0,1]生成隨機數?

[英]How do I generate random numbers from [0,1]?

我想從[0,1]生成隨機數。

import os

int.from_bytes(os.urandom(8), byteorder="big") / ((1 << 64) - 1)

上面的代碼在我的python版本中不起作用。

import random

random.random() 

僅從[0,1)生成隨機變量,並且不包含1。我希望它精確地是[0,1]還有其他方法嗎?

使用Python的random模塊:

import random

# int
x = random.randint(0, 1)  # 0 or 1(both incl.)

# float excl. 1.0
x = random.random()  # float from [0,1)

或,如@ajcr指出並在此處進行描述。:

# from [0.0, 1.0], but upper boundary not guaranteed
x = random.uniform(0, 1)  

由於float的精度和舍入問題適用於所有這些方法,因此可以嘗試作弊並使用decimal模塊:

import decimal

def randfloat():
    decimal.getcontext().prec = 10  # 10 decimal points enough?!
    return decimal.Decimal(0) + decimal.Decimal(random.uniform(0, 1))
# this should include both boundaries as float gets close enough to 1 to make decimal round

>>> decimal.Decimal(0) + decimal.Decimal(0.99999999999)
Decimal('1.000000000')

# while uniform() apparently guarantees the inclusion of the lower boundary

您要搜索的工具可能是random.uniform(0, 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM