使用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で指摘してhereを説明した:。
# 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)'? –
@ajcr私はドキュメントを読んで、random.uniformについてこう書いています: "a +(ba)* random()の浮動小数点丸めに応じて、エンドポイント値bが範囲に含まれる場合と含まれない場合があります。 "だから私はrandom.uniformが良い選択であるかどうかは分かりません。 –
@ Ralf17しかし、それは正確な制限のために 'float'が正確な境界の包含/排他性を保証できないということではありませんか? – schwobaseggl