How to Create a Random Decimal Number Between a Range, Using Random Module

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

For decimal

random_decimal = random.random()

print(random_decimal)

Output:

0.9414759581487204

Create a random decimal number Between a Range

For integer:

random_integer = random.randint(1, 10)

print (random_integer)

Output
3
8

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.

For Decimal,

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)

Output

0.5
2.0

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

Similar Posts