2016-04-10 2 views
0

[0,1]から乱数を生成したい。[0,1]から乱数を生成するにはどうすればよいですか?

import os 

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

私のpythonバージョンでは上記のコードは機能しません。

また

import random 

random.random() 

のみ)0,1 [からランダム変数を生成し、私はこれを行うには、正確に、[0,1]の任意の他の方法になりたい1が含まれていませんか?

+0

'random.uniform(0、1)'? –

+0

@ajcr私はドキュメントを読んで、random.uniformについてこう書いています: "a +(ba)* random()の浮動小数点丸めに応じて、エンドポイント値bが範囲に含まれる場合と含まれない場合があります。 "だから私はrandom.uniformが良い選択であるかどうかは分かりません。 –

+1

@ Ralf17しかし、それは正確な制限のために 'float'が正確な境界の包含/排他性を保証できないということではありませんか? – schwobaseggl

答えて

2

使用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 
+1

私は連続変数または浮動小数点数を生成したいと思います。random.randint(0,1)は整数を与え、random.random()は[0,1] [0,1]ではない。 –

+1

うーん...どんな解像度が必要ですか?完全な浮動小数点精度。あなたはsthと行くことができます。 'random.randint(0、10 ** 6)* 1.0/10 ** 6'のように – schwobaseggl

0

あなたが探しているツールrandom.uniform(0, 1)