我在 python 中使用 random
模块,发现这段代码总是返回 inf
:
import random
print(random.uniform(0, float("inf")))
我想知道为什么以及是否有另一种方法可以做到这一点,这样它就不会总是返回 inf
。
最佳答案
如果您调查random.uniform
来源,就会清楚:
def uniform(self, a, b):
"Get a random number in the range [a, b) or [a, b] depending on rounding."
return a + (b-a) * self.random()
任何带有 float('inf')
的算术都会返回 -inf
或 inf
。
在这种情况下:
b-a
其中 b
是 inf
计算结果为 inf
,inf * self.random()
是 inf
(如果 self.random()
为负,则为 -inf
)和 a + inf
> 是inf
。
关于python - 为什么 random.uniform(0, float ("inf")) 总是返回 inf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55076388/