How to copy floating point number just below the limit?

Functions such as numpy.random.uniform()return floating point values ​​between two boundaries, including the first bound, but excluding the upper bound. That is, it numpy.random.uniform(0,1)can give 0, but it will never lead to 1.

I take such numbers and process them with a function that sometimes returns results outside the range. I can use numpy.clip()to grind values ​​outside the range to 0-1, but unfortunately this limit includes the upper number.

How to specify "number infinitely less than 1" in python?

+4
source share
4 answers

Well, if you use numpy, you can just use 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

[ , , , .]

+5

Python sys float_info epsilon

1 1, float

, -

def clip(num):
    if(num >= 1):
        return 1 - sys.float_info.epsilon
    return num

. , , , , , , .

EDIT - . CPython , , - IronPython, ( ). !

+3

, . 0.9999999 1.0.

+1

. , , ? :

def my_uniform(low=0, high=1):
  import numpy as np
  while True:
    x = np.random.uniform(low, high)
    if x > low and x < high:
      yield x

, , 1 , np.nextafter(1, 0) ?

If your processing returns values ​​outside the valid range and is deterministic, perhaps you should filter the input rather than trim the output.

0
source

All Articles