Explain Codes LogoExplain Codes Logo

How to get a random number between a float range?

python
random-number-generation
float-range
numpy-library
Anton ShumikhinbyAnton Shumikhin·Jan 4, 2025
TLDR
import random print(random.uniform(1.5, 6.5)) # Whoops! Just tossed a floating coin between 1.5 and 6.5.

random.uniform: Accurate and inclusive

The random.uniform(a, b) function is the direct solution for getting a random floating-point number between any two numbers a and b. Remember, random.uniform is inclusive, so both a and b can be exact outputs. This inclusivity provides an edge for cases demanding high precision.

Adjusting decimal points with round

import random rounded_random = round(random.uniform(1.5, 6.5), 2) # I want two digits after ".", nothing more!

If more control over decimal points is what you crave, combining random.uniform with round is the trick. This combo generates a number between a and b, restricted to the number of decimal points you need.

Let numpy do the trick: np.random.uniform

import numpy as np print(np.random.uniform(1.5, 6.5)) # I 💟 math and nums - randomizing the numpy way!

If your journey in data science or scientific computing is inseparable from numpy, an alternative exists: np.random.uniform(). It's quite identical to random.uniform but tuned for array computations which NumPy is famous for.

All-purpose weapon

random.uniform can be a secret weapon in many fields, including but not limited to simulation, gaming, and AI. From modelling real-world randomness to introducing unpredictability in games, it's very wieldy.

Tackling the edge case beasts

While employing random.uniform, stay on guard against edge cases. Always ensure a is less than b or be ready to catch ValueError. If you're enclosed in loops or your function is a party spot, visited multiple times, don't forget to seed your random number generator to keep the results repeatable.

When integers won't suffice

Rely on random.uniform whenever your range can't be represented simply with integers. Let's say, you have a shop in a role-play game and need to generate a random price for a mystical potion between $10.50 and $10.75.

Preserve memory for those large datasets

In case of large datasets, it's often advisable to limit the decimal places of your floats. This doesn't just save memory but also boosts performance. Team up random.uniform with round, and wrestle down those obnoxiously large random floats in style.