x=1:3; accumulate(+, x)
To make a cumulative sum from left which yields [1,3,6].
But how I accumulatr from right efficiently? I know I can do x=1:3; reverse(accumulate(+,reverse(x)))
But i think reverse would make this inefficient for large arrays eg with 1 billion elements. Looking through the doc I couldn’t find any mention of accumulate from right.
julia> accumulate(+, Iterators.reverse(x))
ERROR: MethodError: no method matching similar(::Base.Iterators.Reverse{Array{Int64,1}}, ::Type{Int64})
Hmm. This seems a bit unfortunate. Is it a general problem that operations on wrapped arrays sometimes to try to allocate a similar(::WrapperType{Array{...}}) and failing?
Also, this fails,
julia> reverse(Iterators.reverse(r))
ERROR: MethodError: no method matching reverse(::Base.Iterators.Reverse{Array{Int64,1}})
while this works, of course
julia> Iterators.reverse(Iterators.reverse(x))
It seems hard to get these things to compose well.
@Adriel i dont mean to be rude but doubt it’s efficient as it’s vcating and summing alot more then necessary. I guess i would write a loop. But then the same can be said of accumulate? It can be done with a loop, the curious thing is that it can loop from left but not from right. You have foldl and foldr so why not an accumulater that is efficient?
cumsum of arrays in Julia has the advantages of being much more accurate than a straightforward loop for floating point data. That algorithm requires a random access array, such as a view, not an iterator, however.
~2.2 sec for 100,000,000 elements v ~ 0.9 sec for the left-to-right version, so a bit average
May be able to use the end result of accsum for the sum(), and vector subtract
z = accumulate(+, x);
z2 = z[end] .- [0; z[1:end-1]];
Shouldn’t the focus be on making this work with Iterators.reverse?
julia> accumulate(+, Iterators.reverse(r))
ERROR: MethodError: no method matching similar(::Base.Iterators.Reverse{Array{Int64,1}}, ::Type{Int64})
Apparently, there’s a similar method missing. I tried implementing it, but it seems I need a debugger to figure out what’s going on. (Time to learn Rebugger.jl!)