Generating random decimal numbers is a common task in many programming projects. In Python, you can easily create a random decimal number between a range by using the
random module. In this blog post, we’ll show you how to do just that.
Before starting with the actual answer let’s first see, How to create a random decimal number using the random module
Create a random decimal number
random_decimal = random.random() print(random_decimal)
Create a random decimal number Between a Range
random_integer = random.randint(1, 10) print (random_integer) Output
By comparing the above examples, We could see for integers, we can able to provide a range So that I can generate random values within the range 0 -> 10.
It will always generate a random number between 0 -> 0.999999
To bypass the restriction, We can use a quick hack
To create a random decimal number between 0 -> 5, We can just multiply the number 5 with the end results 🙂
random_decimal = random.random() final=random_decimal * 5 print(final)
The above code will generate a random decimal number between 0 to 5, Similarly, we can use it for any range of values
To know more about Randomization check here