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

后端 未结 3 1549
春和景丽
春和景丽 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:37

    Aside from the different representation of lists and arrays NumPys arange works by multiplying instead of repeated adding. It's more like:

    def my_range2(start, stop, step):
        i = 0
        while start+(i*step) < stop:
            yield start+(i*step)
            i += 1
    

    Then the output is completely equal:

    >>> np.arange(0, 1, 0.1).tolist() == list(my_range2(0, 1, 0.1))
    True
    

    With repeated addition you would "accumulate" floating point rounding errors. The multiplication is still affected by rounding but the error doesn't accumulate.


    As pointed out in the comments it's not really what is happening. As far as I see it it's more like:

    def my_range2(start, stop, step):
        length = math.ceil((stop-start)/step)
        # The next two lines are mostly so the function really behaves like NumPy does
        # Remove them to get better accuracy...
        next = start + step
        step = next - start
        for i in range(length):
            yield start+(i*step)
    

    But not sure if that's exactly right either because there's a lot more going on in NumPy.

提交回复
热议问题