Comparing NumPy arange and custom range function for producing ranges with decimal increments

后端 未结 3 1484
春和景丽
春和景丽 2021-01-12 02:52

Here\'s a custom function that allows stepping through decimal increments:

def my_range(start, stop, step):
    i = start
    while i < stop:
        yiel         


        
3条回答
  •  情话喂你
    2021-01-12 03:36

    While arange does step through the range in a slightly different way, it still has the float representation issue:

    In [1358]: np.arange(0,1,0.1)
    Out[1358]: array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])
    

    The print hides that; convert it to a list to see the gory details:

    In [1359]: np.arange(0,1,0.1).tolist()
    Out[1359]: 
    [0.0,
     0.1,
     0.2,
     0.30000000000000004,
     0.4,
     0.5,
     0.6000000000000001,
     0.7000000000000001,
     0.8,
     0.9]
    

    or with another iteration

    In [1360]: [i for i in np.arange(0,1,0.1)]  # e.g. list(np.arange(...))
    Out[1360]: 
    [0.0,
     0.10000000000000001,
     0.20000000000000001,
     0.30000000000000004,
     0.40000000000000002,
     0.5,
     0.60000000000000009,
     0.70000000000000007,
     0.80000000000000004,
     0.90000000000000002]
    

    In this case each displayed item is a np.float64, where as in the first each is float.

提交回复
热议问题