Question

How do I get a random decimal.Decimal instance? It appears that the random module only returns floats which are a pita to convert to Decimals.

Was it helpful?

Solution

What's "a random decimal"? Decimals have arbitrary precision, so generating a number with as much randomness as you can hold in a Decimal would take the entire memory of your machine to store.

You have to know how many decimal digits of precision you want in your random number, at which point it's easy to just grab an random integer and divide it. For example if you want two digits above the point and two digits in the fraction (see randrange here):

decimal.Decimal(random.randrange(10000))/100

OTHER TIPS

From the standard library reference :

To create a Decimal from a float, first convert it to a string. This serves as an explicit reminder of the details of the conversion (including representation error).

>>> import random, decimal
>>> decimal.Decimal(str(random.random()))
Decimal('0.467474014342')

Is this what you mean? It doesn't seem like a pita to me. You can scale it into whatever range and precision you want.

If you know how many digits you want after and before the comma, you can use:

>>> import decimal
>>> import random
>>> def gen_random_decimal(i,d):
...  return decimal.Decimal('%d.%d' % (random.randint(0,i),random.randint(0,d)))

...
>>> gen_random_decimal(9999,999999) #4 digits before, 6 after
Decimal('4262.786648')
>>> gen_random_decimal(9999,999999)
Decimal('8623.79391')
>>> gen_random_decimal(9999,999999)
Decimal('7706.492775')
>>> gen_random_decimal(99999999999,999999999999) #11 digits before, 12 after
Decimal('35018421976.794013996282')
>>>

The random module has more to offer than "only returning floats", but anyway:

from random import random
from decimal import Decimal
randdecimal = lambda: Decimal("%f" % random.random())

Or did I miss something obvious in your question ?

decimal.Decimal(random.random() * MAX_VAL).quantize(decimal.Decimal('.01'))

Yet another way to make a random decimal.

import random
round(random.randint(1, 1000) * random.random(), 2)

On this example,

  • random.randint() generates random integer in specified range (inclusively),
  • random.random() generates random floating point number in the range (0.0, 1.0)
  • Finally, round() function will round the multiplication result of the abovementioned values multiplication (something long like 254.71921934351644) to the specified number after the decimal point (in our case we'd get 254.71)
import random
y = eval(input("Enter the value of y for the range of random number : "))
x = round(y*random.random(),2)  #only for 2 round off 
print(x)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top