python 隨機數生成

嘰了咣啷biang發表於2012-06-24

函式random.randrange可生成一個隨機整數,範圍從第一個引數值開始,範圍從第一個引數值開始,一直到(但不包括)第二個引數。假如randrange真的能隨機的生出整數,那麼每次呼叫函式時範圍中的每個數字的出現率都應該是均等的。

 

示例程式碼

 

import random

for i in range(1,21):
    print "%10d" % (random.randrange(1,7)),

    if i % 5 == 0:
        print

import random

frequency1 = 0
frequency2 = 0
frequency3 = 0
frequency4 = 0
frequency5 = 0
frequency6 = 0

for roll in range(1,6001):
    face = random.randrange(1,7)

    if face == 1:
        frequency1 += 1
    elif face == 2:
        frequency2 += 1
    elif face == 3:
        frequency3 += 1
    elif face == 4:
        frequency4 += 1
    elif face == 5:
        frequency5 += 1
    elif face == 6:
        frequency6 += 1
    else:
        print "should never get here!"

print "Face %13s" % "Frequency"
print "   1 %13d" % frequency1
print "   2 %13d" % frequency2
print "   3 %13d" % frequency3
print "   4 %13d" % frequency4
print "   5 %13d" % frequency5
print "   6 %13d" % frequency6

相關文章