Python random.uniform()

您所在的位置:网站首页 编程uniform Python random.uniform()

Python random.uniform()

2024-07-10 12:12| 来源: 网络整理| 查看: 265

Python random.uniform()

uniform()是Python 3中随机库中指定的一个方法。

现在,在一般的、日复一日的任务中,总是需要在一个范围内生成随机数。正常的编程结构需要一个比一个字更多的方法来实现这个特殊的任务。在python中,有一个内置的方法,”uniform()”,它可以轻松地完成这个任务,而且只用一个词。这个方法被定义在 “随机 “模块中

语法: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


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3