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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With