如何将浮点数限制为略低于限制?
类似 numpy.random.uniform()< 的函数/code>
返回两个边界之间的浮点值,包括第一个边界,但不包括顶部边界。也就是说,numpy.random.uniform(0,1) 可能会产生 0,但永远不会产生 1。
我正在获取这些数字并使用有时返回超出范围的结果的函数来处理它们。我可以使用 numpy.clip()
将超出范围的值削减回 0-1,但不幸的是,该限制包含最高数字。
如何在Python中指定“无限小于1的数字”?
Functions like numpy.random.uniform()
return floating point values between a two bounds, including the first bound but excluding the top one. That is, numpy.random.uniform(0,1)
may yield 0 but will never result in 1.
I'm taking such numbers and processing them with a function that sometimes returns results outside of the range. I can use numpy.clip()
to chop values outside of the range back to 0-1, but unfortunately that limit is inclusive of the top number.
How do I specify "the number infinitesimally smaller than 1" in python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,如果你使用 numpy,你可以简单地使用 numpy。 nextafter:
请注意(至少对我来说):
顺便说一句,第二个 @Robert Kern 的观点是有时 random.uniform 将包含除 (0, 1) 之外的某些输入的上限:
[我普遍认为可能有更好的方法来解决这个问题。]
Well, if you're using numpy, you can simply use numpy.nextafter:
Note that (at least for me):
Incidentally, to second @Robert Kern's point that sometimes random.uniform will include the upper bound for some inputs other than (0, 1):
[I share the general sense that there is probably a better way to approach this problem.]
Python 的 sys 提供了一个带有
epsilon 的
属性并定义为float_info
结构体所以我认为类似的东西
应该可以解决问题。尽管这通常很糟糕,并且可能有很多原因让您永远不应该尝试这样做。
编辑我刚刚观察到这样一个原因 - 实施。虽然 CPython 可以满足您的期望,但我的第一个选择是 IronPython,它不(虽然这是一个错误)。你们要被警告!
Python's sys provides an
float_info
struct with anepsilon
attribute and is defined asSo I would suppose something like
should do the trick. Although this is generally bad, and there are probably tons of reasons why you should never attempt this.
EDIT I just observed one such reason - implementation. While CPython does what you'd expect, my first go-to choice is IronPython, which doesn't (although it's a bug). Ye be warned!
在大多数实际情况下,您不需要无限小,您可以近似它。因此,对于您的示例,我将使用 0.9999999 而不是 1.0。
In most practical cases you don't need to be infinitesimally smaller, you can approximate it. So for your example I'd use 0.9999999 instead of 1.0.