python中的随机十进制

问题描述:

如何获取随机 decimal.Decimal 实例?看来,随机模块仅返回浮点数,而浮点数是要转换为小数的皮塔饼.

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.

什么是随机十进制"?小数具有任意精度,因此生成具有尽可能多的随机性的数字将占用机器的整个内存.

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