Unexpected behavior of vectorized += with duplicate indices

There are two things going on here. One is that lhs .+= 1 is the very simple transform that expands to lhs .= lhs .+ 1. And what you have on the left hand side is x[indices] — which, when moved onto the right-hand side, becomes the standard copying indexing behavior. So you end up with:

x[[2,2]] .= x[[2,2]] .+ 1

Now if you’re enterprising, you can remember that @views will avoid making that copy! So you can do @views x[[indices]] .+= 1 — and indeed that returns [0.0, 2.0, 0.0]. But now you’re at the edge of hitting the second problem, and that’s that Julia’s semantics here simply aren’t very well defined. Broadcast makes a “best-effort” attempt at avoiding strange aliasing behaviors, but it’s not 100% clear what the behaviors should be. This is How should in-place broadcasting with repeated indices behave? · Issue #31392 · JuliaLang/julia · GitHub.

1 Like