How to create a random number of a given decimal point between 2 digits in Python?

I want to create a random number with 1 decimal point between min_time and m_time, e.g. 0.3

Now I have a really fancy solution

m_time = 0.5 min_time = 0.2 float(randint(int(min_time * 10), int(m_time * 10))) / 10 

it works, but I wonder if there is a better solution?

+7
source share
3 answers

I think the preferred way is to evenly select the floating number between min_time and max_time , and then use the built-in round (up to the first decimal place):

 round(random.uniform(min_time, max_time), 1) 
+7
source
 import decimal import random 

- i and j belong to your limit, like 2 and 3

 decimal.Decimal('%d.%d' % (random.randint(0,i),random.randint(0,j))) 
+6
source

I think you are doing well. Although you could also write this as

 0.1*randint(int(min_time * 10), int(m_time * 10)) 

Another obvious option is

 round(random.random()*(m_time-min_time)+min_time, 1) 
+2
source

All Articles