Python random.uniform()
Python random.uniform()
uniform() is a method specified in the random library in Python 3.
Now, in common, day-to-day tasks, you often need to generate random numbers within a range. Normal programming constructs require more than a single word to implement this particular task. In Python, there is a built-in method, “uniform(),” that can easily accomplish this task with just one word. This method is defined in the “random” module.
Syntax: uniform(int x, int y).
Parameters: x specifies the lower bound of the random number to be generated. y specifies the upper bound of the random number to be generated.
Return Value: Returns a floating-point random number generated between the lower bound and the upper bound.
Code #1: Code for generating a floating-point random number.
# Python 3 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))
Output:
The random number generated between 4 and 9 is: 7.494931618830411
Applications: This function has many possible applications, some notable of which are generating random numbers in casino games, for use in lotteries, or for custom games. Here’s a game where the winner is determined by how close the number is to a certain value.
Code #2: Application of uniform() – a game
# 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)
#findclosest
diffa = math.fabs(winner - player1)
diffb = math.fabs(winner - player2)
diffc = math.fabs(winner - player3)
#printingwinner
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")
Output:
The winner of game is : Player2