Python 如何从范围中获取随机十进制数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40972438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:16:26  来源:igfitidea点击:

How to get random Decimal number from range?

pythonpython-2.7randomdecimal

提问by Milano

I'm looking for a way how to generate random Decimalnumber within some range. For example -

我正在寻找一种如何Decimal在某个范围内生成随机数的方法。例如 -

>>> random.choice(range(Decimal(1.55,3.89)))

>>> 1.89

Is it possible to do that with random? I want to preserve 2 decimal places.

有可能用随机来做到这一点吗?我想保留 2 个小数位。

random.choice(range(Decimal(1.55,3.89))) 

returns >>> 0

返回 >>> 0

回答by ettanany

You can use random.randrange()like this:

你可以这样使用random.randrange()

import random
import decimal

decimal.Decimal(random.randrange(155, 389))/100

And then use float()to get your desired output:

然后使用float()以获得所需的输出:

>>> float(decimal.Decimal(random.randrange(155, 389))/100)
3.14
>>> float(decimal.Decimal(random.randrange(155, 389))/100)
1.91

As mentioned by @jsbueno in the comment, you can use generated numbers in formatted strings without converting them to floats:

正如@jsbueno 在评论中提到的,您可以在格式化字符串中使用生成的数字,而无需将它们转换为浮点数:

>>> '{}'.format(decimal.Decimal(random.randrange(155, 389))/100)
'3.85'

You may need to use just float()like below:

您可能需要float()像下面这样使用:

>>> float(random.randrange(155, 389))/100
2.38
>>> float(random.randrange(155, 389))/100
3.72

Note:

笔记:

In random.randrange(155, 389), 155is included in the range, but 389is not, if you want to include 389, you should use random.randrange(155, 390). This is mentioned by @mhawke in the comments below.

random.randrange(155, 389),155包含在范围内,但389不是,如果要包含389,则应使用random.randrange(155, 390). @mhawke 在下面的评论中提到了这一点。

回答by Cenfus

You could generate an integer in the range 100x your range, then divide by 100. Would save importing Decimal, and you wouldn't have to deal with cutting down on significant figures as you would with floats.

您可以在 100 倍范围内生成一个整数,然后除以 100。将节省导入 Decimal,并且您不必像处理浮点数那样处理减少有效数字的问题。

>>> import random

>>> random_decimal = random.randint(155, 389)/100
>>> print(random_decimal)
2.12

Or to output more values:

或者输出更多值:

>>> for i in range(10):
>>>    print(random.randint(155, 389)/100)
2.69
3.84
3.53
3.87
1.56
2.12
2.7
2.4
3.31
3.28