我如何将浮点数限制在一个极限之下? [英] How do I clip a floating-point number to just below a limit?

查看:168
本文介绍了我如何将浮点数限制在一个极限之下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

numpy。 random.uniform() 返回两个边界之间的浮点值,包括第一个边界,但不包括顶部边界。也就是说, numpy.random.uniform(0,1)可能会产生0,但永远不会产生1.

我正在采取这样的数字,并使用函数来处理它们,有时会返回范围之外的结果。我可以使用 numpy.clip() 将范围之外的值切回到0-1,但是不幸的是,这个限制是顶部数字的包括

如何在python中指定数目无限小于1?

解决方案

'使用numpy,你可以简单地使用 numpy.nextafter

 >>> import numpy 
>>> numpy.nextafter(1,0)
0.99999999999999989

请注意(至少对我而言) :

 >>> import sys 
>>> 1-sys.float_info.epsilon
0.9999999999999998
>>> numpy.nextafter(1,0) - (1-sys.float_info.epsilon)
1.1102230246251565e-16
>>> numpy.nextafter(1,0)> (1-sys.float_info.epsilon)
True

顺便说一句,对于@Robert Kern指出有时random.uniform 包含除(0,1)以外的一些输入的上界:

 >>> import random,numpy 
>>> numpy.nextafter(0,1)
4.9406564584124654e-324
>>> random.uniform(0,numpy.nextafter(0,1))
0.0
>>> random.uniform(0,numpy.nextafter(0,1))
0.0
>>> random.uniform(0,numpy.nextafter(0,1))
4.9406564584124654e-324



< [我同意一般意义上说,可能有更好的方法来解决这个问题。]

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?

解决方案

Well, if you're using numpy, you can simply use numpy.nextafter:

>>> import numpy
>>> numpy.nextafter(1, 0)
0.99999999999999989

Note that (at least for me):

>>> import sys
>>> 1-sys.float_info.epsilon
0.9999999999999998
>>> numpy.nextafter(1, 0) - (1-sys.float_info.epsilon)
1.1102230246251565e-16
>>> numpy.nextafter(1, 0) > (1-sys.float_info.epsilon)
True

Incidentally, to second @Robert Kern's point that sometimes random.uniform will include the upper bound for some inputs other than (0, 1):

>>> import random, numpy
>>> numpy.nextafter(0,1)
4.9406564584124654e-324
>>> random.uniform(0, numpy.nextafter(0,1))
0.0
>>> random.uniform(0, numpy.nextafter(0,1))
0.0
>>> random.uniform(0, numpy.nextafter(0,1))
4.9406564584124654e-324

[I share the general sense that there is probably a better way to approach this problem.]

这篇关于我如何将浮点数限制在一个极限之下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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