Integer overflow in cumprod (cumulative product) output

The cumulative product vector of a series of linear positive numbers (show in plot(cump1) ) contains negative num and zeros(in plot(cump2)). I checked available documentations carefully and still was in dark.

twoNmu=1;ns=Int(1e3)
 cump1=Int64[]
 for i in 0:(ns-1)
  push!(cump1,twoNmu+i)
 end
 #cumpt1=hcat(cump1)
 cump2=cumprod(cump1)#default as one
 plot(cump1)
 plot(cump2)

This is integer overflow. If you want to work with huge integers without overflow, use BigInt. (Or use floating-point calculations.)

See e.g. the manual on overflow or this discussion or other similar discussions.

2 Likes

Thanks, I made a trial according to big() (updated to BigInt()?) suggested among posts, but it still doesn’t work.

twoNmu=1;ns=Int(1e3)
 cump1=Int64[]
 cump2=Array{BigInt}(undef,1000,1) #overwritten to Int64 later at "cump2=..."#

 for i in 0:(ns-1)
  push!(cump1,twoNmu+i)
 end
 println(size(cump1),size(cump2))
 cump1=hcat(cump1)
 cump2=BigInt.(cumprod(cump1,dims=1)) #doesn't work
 plot(cump2)

You have to convert to BigInt before the overflow happens. E.g., cump1 = BigInt[].

4 Likes

this is like float(Int(floor(3.14))), you can’t recover what is already lost, so you have to compute the cumprod with big integer to begin with.

2 Likes