Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random number of given decimal point between 2 number in Python?

Tags:

python

random

I want to generate a random number with 1 decimal point between min_time and m_time, like 0.3

Now I have a really quirk solution

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

it works, but I'm wondering if there is a better solution?

like image 346
mko Avatar asked Oct 06 '12 04:10

mko


2 Answers

I think the preferred way is to uniformly choose a floating number between min_time and max_time and then use the built-in round function (to the first decimal place):

round(random.uniform(min_time, max_time), 1)
like image 78
Andy Hayden Avatar answered Nov 04 '22 11:11

Andy Hayden


import decimal
import random

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

decimal.Decimal('%d.%d' % (random.randint(0,i),random.randint(0,j)))
like image 44
Rajendra Avatar answered Nov 04 '22 10:11

Rajendra