random Decimal in python

2020-02-26 07:11发布

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.

7条回答
啃猪蹄的小仙女
2楼-- · 2020-02-26 07:30

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)
查看更多
放荡不羁爱自由
3楼-- · 2020-02-26 07:38
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)
查看更多
做自己的国王
4楼-- · 2020-02-26 07:41
decimal.Decimal(random.random() * MAX_VAL).quantize(decimal.Decimal('.01'))
查看更多
霸刀☆藐视天下
5楼-- · 2020-02-26 07:47

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.

查看更多
该账号已被封号
6楼-- · 2020-02-26 07:48

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 ?

查看更多
forever°为你锁心
7楼-- · 2020-02-26 07:52

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
查看更多
登录 后发表回答