Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to find random floats in range [a,b] in python?

I'm trying to generate in python random floats in the range of [0.8,0.9] , but unfortanetly all the tools i found could only generate randoms in the range of [a,b) for floats. ( like Random.uniform(a,b) )

Meanwhile , I tried doing something like this :

uniform(0.8,0.90000000001)

but thats realy bad

any ideas ?

like image 969
RanZilber Avatar asked Dec 02 '22 03:12

RanZilber


2 Answers

The difference between [0.8, 0.9] and [0.8,0.9) is vanishingly small. Given the limitations of binary floating-point, I don't think there even is a difference, since 0.9 can't be precisely represented anyway. Use [0.8,0.9).

like image 83
Ned Batchelder Avatar answered Dec 22 '22 16:12

Ned Batchelder


Quoting the random.uniform() docstring:

Get a random number in the range [a, b) or [a, b] depending on rounding.

So you don't even know if the endpoint is included or not. But you should not care either -- there are 900719925474100 floating point numbers in the range [0.8, 0.9]. It will take a lifetime until a single one of them occurs anyway, so there is no practical difference to including the endpoint or not, even if the endpoint can be represented exactly as a floating point number.

like image 44
Sven Marnach Avatar answered Dec 22 '22 15:12

Sven Marnach