views:

723

answers:

4

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

+11  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.

Kiv
+5  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')
>>>
Vinko Vrsalovic
If it matters here: the fractional part of such a number would not be uniformly random, due to removal of leading zeroes. You can't get '2.0something' out of it.
bobince
I considered this too, but it would be neater to take (4, 6) as the arguments instead of (9999, 999999) and then just use 10**4 - 1, 10**6 - 1 in the function body.
Kiv
I agree with both comments :-)
Vinko Vrsalovic
Or something like "%d.%0*d" % ( random.randint(0,10**ni-1), nd, random.randint(0,10**nd-1) ); assuming nd and ni are the number of digits requested
S.Lott
@S.Lott: Ah, that takes care of the leading zeros. Nice one.
Kiv
+12  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:

decimal.Decimal(random.randrange(10000))/100
bobince
I love this brainfuck. You can't create random Decimals! Only random to desired precision!
kaizer.se
A: 

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 ?

bruno desthuilliers