random Decimal in python

后端 未结 7 1174
野趣味
野趣味 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:21

    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
    

提交回复
热议问题