There may come a time when a developer has to create an “RNG” system, which is the random number generator. This can easily be done in Python using some built-in method of the “random” library. There are two methods in the “random” library that can be used to create random floating-point numbers. These methods are “random()” and “uniform”.
This post will illustrate the use of these two methods to create random floating-point numbers in Python.
Method 1: Generate Random Number Using the “random()” Method
The random() method generate floating values that only range from “0” to “1”, and to test this out, you can use the following code snippet:
When this code is executed, it will produce a random floating-point value between 0 and 1 onto the terminal window:
Having floating point values ranging only between 0 and 1 is not something that everyone wants. But, you can always alter the result using some simple mathematics. For example, to get a result between 1 and 10, you can simply multiply the output by 10:
This will give us the following output:
There is one more thing that most users want, and that is to round off the decimal part up to a specific number.
To do this, the user can utilize the round() method. In the first argument of the round method, the floating-point value is provided and in the second argument, the number of values after the decimal point is given.
To demonstrate this, take the following code example:
In this above code, the number of decimal point values has been set to three, when this code is executed, it produces the following output:
That is how the user can utilize the random() function to generate random float numbers.
Method 2: Generate Random Number Using the “uniform()” Method
The second method is the uniform() method which is used to generate float numbers between a specific range which is defined inside its arguments. Suppose that the user wants to generate float numbers between 50 and 100, then the user can simply use the following code:
This will generate the following result on the terminal window:
In case the user wants to reduce the numbers after the decimal point, then use the round() method, similar to what has been explained in method 1:
When this code is executed, it produces similar results:
That is how you can utilize the uniform() method to generate random float numbers.
In Python, the user can easily generate random float numbers with the help of the random() and the uniform() methods which belong to the “random” package. The random() method generates a float value between zero and one which can be altered to generate a value between a specific range using simple mathematics. The uniform() method, on the other hand, takes two values as input, which define the range in which the random float value is to be generated.