Julia sum issue

Hi In the below code I am getting wrong summation output

zz=sum((M_B_DG_400[bb,t,c,p]*C_s[c]) for  p in 1:P, t in 1:T, bb in 1:b)

if the value of M_B_DG_400[bb,t,c,p] is zero then value zz should be zero. But it is not showing as zero.
any idea how to correct it.

Can you produce a minimum working example?

Are you sure that M_B_DG_400 is zero everywhere? If it isn’t then the sum wouldn’t be zero of course

julia> sum(x*y for x ∈ 0:1, y ∈ 2:3) # one non-zero value for x
5

julia> sum(x*y for x ∈ fill(0, 2), y ∈ 2:3) # x is all zeros
0

It’s extremely unlikely that Julia’s sum function should have a previously undiscovered bug where it sums all zeros to something non-zero.

I propose that you first check whether
all((M_B_DG_400[bb,t,c,p]*C_s[c] == 0) for p in 1:P, t in 1:T, bb in 1:b)
is true. If it’s not, you’re summing at least one non-zero element and shouldn’t expect the sum to be zero.

If it was true, then check whether

Base.sum((M_B_DG_400[bb,t,c,p]*C_s[c]) for  p in 1:P, t in 1:T, bb in 1:b) == 0

If it is, you must have redefined sum and the problem is not in Julia’s sum but in your own.

If it still looks like a problem in Julia, provide a way to reproducibly reconstruct the arrays M_B_DG_400 and C_s, either by code or by dumping them to file and making that available.

2 Likes