python中的随机十进制 [英] random Decimal in python

查看:74
本文介绍了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

这篇关于python中的随机十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆