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.
问题:
回答1:
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
回答2:
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.
回答3:
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')
>>>
回答4:
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 ?
回答5:
decimal.Decimal(random.random() * MAX_VAL).quantize(decimal.Decimal('.01'))
回答6:
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)
回答7:
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)