Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get random Decimal number from range? [duplicate]

I'm looking for a way how to generate random Decimal number within some range. For example -

>>> random.choice(range(Decimal(1.55,3.89)))

>>> 1.89

Is it possible to do that with random? I want to preserve 2 decimal places.

random.choice(range(Decimal(1.55,3.89))) 

returns >>> 0

like image 402
Milano Avatar asked Dec 05 '16 10:12

Milano


People also ask

How do I generate random decimal numbers in a range in Excel?

Generate a random decimal within a specified rangeEnter the formula =RAND()*([UpperLimit]-[LowerLimit])+[LowerLimit]. For example, if you'd like to generate a random decimal between one and 10, you may enter =RAND()*(10-1)+1. Press the "Enter" key.

Can you do Randbetween with decimals?

In this example, the RANDBETWEEN function generates random numbers between 2 and 4 with a decimal. Since it actually can't generate numbers with decimals the function generates values between 20 to 40. Divide the output with 10 and the range becomes 2.0 to 4.0.

How do you generate unique random numbers within a range in Excel?

Generating a Set of Unique Random Numbers in Excel In a column, use =RAND() formula to generate a set of random numbers between 0 and 1. Once you have generated the random numbers, convert it into values, so that it won't recalculate again and again to make your workbook slow.


1 Answers

You can use random.randrange() like this:

import random
import decimal

decimal.Decimal(random.randrange(155, 389))/100

And then use float() to get your desired output:

>>> float(decimal.Decimal(random.randrange(155, 389))/100)
3.14
>>> float(decimal.Decimal(random.randrange(155, 389))/100)
1.91

As mentioned by @jsbueno in the comment, you can use generated numbers in formatted strings without converting them to floats:

>>> '{}'.format(decimal.Decimal(random.randrange(155, 389))/100)
'3.85'

You may need to use just float() like below:

>>> float(random.randrange(155, 389))/100
2.38
>>> float(random.randrange(155, 389))/100
3.72

Note:

In random.randrange(155, 389), 155 is included in the range, but 389 is not, if you want to include 389, you should use random.randrange(155, 390). This is mentioned by @mhawke in the comments below.

like image 193
ettanany Avatar answered Sep 21 '22 01:09

ettanany