JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.14k stars 5.43k forks source link

`sum(I -> A[I], CartesianIndices(A); dims=1)` needs initial value in order to work #54875

Open vargonis opened 1 month ago

vargonis commented 1 month ago
A = rand(3,4)
sum(I -> A[I], CartesianIndices(A); dims=1) # ERROR: BoundsError: attempt to access 3×4 Matrix{Float64} at index [0, 0]
sum(I -> A[I], CartesianIndices(A); dims=1, init=0.) # now it works

I'm running the following version:

julia> versioninfo() Julia Version 1.10.4 Commit 48d4fd48430 (2024-06-04 10:41 UTC) Build Info: Official https://julialang.org/ release Platform Info: OS: Linux (x86_64-linux-gnu) CPU: 8 × 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz WORD_SIZE: 64 LIBM: libopenlibm LLVM: libLLVM-15.0.7 (ORCJIT, tigerlake) Threads: 1 default, 0 interactive, 1 GC (on 8 virtual cores)

jishnub commented 1 month ago

This also works:

julia> sum(I -> get(A, I, zero(eltype(A))), CartesianIndices(A); dims=1)
1×4 Matrix{Float64}:
 1.48551  1.92315  1.65579  1.628

The issue appears to be that the init is being computed as A[zero(CartesianIndex{2})], which throws the BoundsError