Inverse of cumsum/cumsum!?


#1

Is there an inverse operation for cumsum (resp. cumsum!)?

It’s not diff, exactly, because diff’s output is one element shorter (and so there can’t be a diff!, either).


#2

It should be the result of concatenating the first element with the output of diff.


#3

diff([0; xvec]) would also be correct


#4

Picking this up, you could go for

function cumsum0(dx::Vector, x0 = zero(eltype(dx)))
        n = length(dx) + 1
        x = similar(dx, n)
        x[1] = x0     
        for i in 2:n
                x[i] = x[i-1] + dx[i-1] 
        end
        x
end

such that diff(cumsum0(x)) ≈ x and cumsum0(diff(x), x[1]) ≈ x. I have similar in my juliarc.


#5

Sorry, I was a bit unclear - of course it’s easy to do. :slight_smile:

I was just wondering if there’s a function in Base for it - especially an allocation-free in-place version (the inverse of cumsum!). It would come in handy, at times, and would make things nicely symmetrical.


#6

You might be interested in this issue: https://github.com/JuliaLang/julia/issues/26361


#7

diffset() might not be too bad, though it could still be mistaken as a complement (A union B) type of operation
Technically it should be like an A complement union B sort of operator, so maybe compunion() would be ok
It might be nice to have a Base.Sets pigeon-hole for specifically set-based operators