uniform()是在Python 2和Python 3中的隨機庫中指定的方法。
如今,在日常工作中,總是需要生成一定範圍內的隨機數。普通的編程結構需要一種方法來完成一個特定任務,而不僅僅是一個單詞。在python中,有一個內置方法“uniform()”,隻需一個單詞即可輕鬆完成此任務。此方法在“random”模塊中定義
語法:uniform(int x,int y)
參數:
x指定生成所需隨機數的下限。
y指定生成所需隨機數的上限。
返回:返回在下限和上限之間生成的浮點隨機數
代碼1:生成浮點隨機數的代碼。
# Python3 code to demonstrate
# the working of uniform()
# for using uniform()
import random
# initializing bounds
a = 4
b = 9
# printing the random number
print("The random number generated between 4 and 9 is:", end ="")
print(random.uniform(a, b))
輸出:
The random number generated between 4 and 9 is:7.494931618830411
應用:
有許多可能的應用程序可以考慮此函數,其中一些值得注意的是在娛樂場遊戲中為彩票或自定義遊戲生成隨機數。
下麵是根據接近度確定贏家的遊戲。
代碼2:uniform()的應用程序-遊戲
# Python3 code to demonstrate
# the application of uniform()
# for using uniform()
import random, math
# initializing player numbers
player1 = 4.50
player2 = 3.78
player3 = 6.54
# generating winner random number
winner = random.uniform(2, 9)
# finding closest
diffa = math.fabs(winner - player1)
diffb = math.fabs(winner - player2)
diffc = math.fabs(winner - player3)
# printing winner
if(diffa < diffb and diffa < diffc):
print("The winner of game is:", end ="")
print("Player1")
if(diffb < diffc and diffb < diffa):
print("The winner of game is:", end ="")
print("Player2")
if(diffc < diffb and diffc < diffa):
print("The winner of game is:", end ="")
print("Player3")
輸出:
The winner of game is:Player2
相關用法
注:本文由純淨天空篩選整理自manjeet_04大神的英文原創作品 Python Number | uniform() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。