Q:

random Decimal in python

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.

A:

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

A:

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.

A:

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')
>>>

