题
我如何获得随机 decimal.Decimal
实例?看来随机模块只返回浮点数,这些浮点数是转换为小数的皮塔饼。
解决方案
什么是“随机小数”?小数具有任意精度,因此生成一个具有尽可能大的随机性的数字将占用机器的整个内存来存储。
您必须知道随机数需要多少位十进制精度,此时很容易获取一个随机整数并将其除以。例如,如果您想要小数点上方两位数字和分数中两位数字(请参阅 兰德兰奇在这里):
decimal.Decimal(random.randrange(10000))/100
其他提示
从标准库参考:
要从浮法创建一个十进制,首先将它转换为字符串。这用作转化的细节(包括表示错误)的显式提醒。
>>> import random, decimal
>>> decimal.Decimal(str(random.random()))
Decimal('0.467474014342')
这是什么意思?它似乎并不像一个皮塔给我。你可以把它大规模进入你想要的任何范围和精度。
如果你知道你之后加逗号前多少位愿意,你可以使用:
>>> import decimal
>>> import random
>>> def gen_random_decimal(i,d):
... return decimal.Decimal('%d.%d' % (random.randint(0,i),random.randint(0,d)))
...
>>> gen_random_decimal(9999,999999) #4 digits before, 6 after
Decimal('4262.786648')
>>> gen_random_decimal(9999,999999)
Decimal('8623.79391')
>>> gen_random_decimal(9999,999999)
Decimal('7706.492775')
>>> gen_random_decimal(99999999999,999999999999) #11 digits before, 12 after
Decimal('35018421976.794013996282')
>>>
在随机模块具有多个提供比“仅返回浮动”,但无论如何:
from random import random
from decimal import Decimal
randdecimal = lambda: Decimal("%f" % random.random())
还是我错过了一些东西明显在你的问题?
decimal.Decimal(random.random() * MAX_VAL).quantize(decimal.Decimal('.01'))
另一种生成随机小数的方法。
import random
round(random.randint(1, 1000) * random.random(), 2)
在这个例子中,
- random.randint() 生成指定范围(含)内的随机整数,
- 随机.随机() 生成 (0.0, 1.0) 范围内的随机浮点数
- 最后, 圆形的() 函数会将上述值相乘的乘法结果(长如 254.71921934351644)四舍五入到小数点后的指定数字(在我们的例子中我们得到 254.71)
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)
不隶属于 StackOverflow