Issue
What exactly is numpy doing when you assign values outside the bounds of the array? Does it pose a risk of overwriting some area of the memory currently used by something else?
In this example, it writes row 9 to all ones. I was hoping to use this to get around an edge case, but I can't find any documentation on this behavior on the numpy pages for assigning or broadcasting.
import numpy as np
x = np.zeros([10, 5])
x[9:11] = 1
Edit per "solved by this other question": I understand what it is doing and how it works. The question that I still have is if there is any risk of memory corruption or if the non-existent slice indices are ignored when writing/assigning.
Solution
From the numpy docs Slicing and striding
You may use slicing to set values in the array, but (unlike lists) you can never grow the array. The size of the value to be set in x[obj] = value must be (broadcastable to) the same shape as x[obj].
When indexing, numpy strives for symmetry between getting and setting values. If a slice overflows a list when you get a value, it is not considered and error:
>>> l = [1,2,3]
>>> l[1:99]
[2, 3]
Similarly, when you assign a slice, numpy drops anything that would overflow. With x[9:11] = 1
, numpy selected the single row that does not overflow the underlying buffer and broadcast a 1
. Numpy reduces the range for assignment and there is no overflow. In your case, you wanted to assign 2 rows but numpy modified your assignment and only set 1 row.
One could argue whether that is a good thing. But if you are concerned about overflowing operations, you need to check the dimensions yourself.
Answered By - tdelaney
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.