How to get a random number between a float range?

PythonRandomFloating Point

Python Problem Overview

randrange(start, stop) only takes integer arguments. So how would I get a random number between two float values?

Python Solutions

Solution 1 - Python

Use random.uniform(a, b):

>>> random.uniform(1.5, 1.9)

Solution 2 - Python

if you want generate a random float with N digits to the right of point, you can make this :

round(random.uniform(1,2), N)

the second argument is the number of decimals.

Solution 3 - Python

random.uniform(a, b) appears to be what your looking for. From the docs:

> Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

See here.

Solution 4 - Python

From my experience dealing with python, I can only say that the random function can help in generating random float numbers. Take the example below;

import random

# Random float number between range 15.5 to 80.5
print(random.uniform(15.5, 80.5))

# between 10 and 100
print(random.uniform(10, 100))
The random.uniform() function returns a random floating-point number between a given range in Python

The two sets of code generates random float numbers. You can try experimenting with it to give you what you want.

Solution 5 - Python

Most commonly, you'd use:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

Python provides other distributions if you need.

If you have numpy imported already, you can used its equivalent:

import numpy as np
np.random.uniform(a, b) # range [a, b)

Again, if you need another distribution, numpy provides the same distributions as python, as well as many additional ones.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMantis TobogganView Question on Stackoverflow
Solution 1 - PythonYuri StukenView Answer on Stackoverflow
Solution 2 - PythonBaurin LezaView Answer on Stackoverflow
Solution 3 - PythongarnertbView Answer on Stackoverflow
Solution 4 - PythonDrosnickXView Answer on Stackoverflow
Solution 5 - PythonstwykdView Answer on Stackoverflow