random Decimal in python

后端 未结 7 1190
野趣味
野趣味 2020-12-31 08:24

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条回答
  •  没有蜡笔的小新
    2020-12-31 09:05

    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.

提交回复
热议问题