Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 580
ashirley Avatar asked Jan 13 '09 14:01

ashirley


People also ask

How do you generate random decimals?

1. Select a blank cell, and type =RAND() into it, and then drag the fill handle to fill the range you need with the formula. 2. Then select the range you have applied the formula, and click the Increase Decimal button or Decrease Decimal button under Home tab to specify the decimal numbers.

How do you generate a random float between 0 and 1 in Python?

To get a random number between 0 and 1 in Python, use the random. uniform() method. The random. uniform() method accepts two numbers and returns the random floating number between them.

How do I get a random number in Python?

Random integer values can be generated with the randint() function. This function takes two arguments: the start and the end of the range for the generated integer values. Random integers are generated within and including the start and end of range values, specifically in the interval [start, end].


2 Answers

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
like image 153
bobince Avatar answered Oct 12 '22 00:10

bobince


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.

like image 31
Kiv Avatar answered Oct 11 '22 23:10

Kiv