Skip to content
Easy Framework

Cumulative Sum

A cumulative sum keeps a running total. At each position, include the current value and every value before it.

Your task

Implement cumulative_sum(x) for a floating-point vector of shape (n,). Return a vector of the same shape, dtype and device, leaving x unchanged.

output[i] = x[0] + x[1] + ... + x[i]

For [5, 0, -3, 2], return [5, 5, 2, 4]:

  • Start with 5.
  • Adding 0 keeps the total at 5.
  • Adding -3 reduces it to 2.
  • Adding 2 brings it to 4.

Negative inputs can make the running total decrease. Do not sort the input, replace negative values or return only the final total.

This is an inclusive cumulative sum: the first output is x[0], not zero. A one-element input is unchanged in value; an empty input returns shape (0,). For a nonempty input, the last result is the sum of the whole vector, subject to floating-point rounding.

Use torch.cumsum(x, dim=0) or jnp.cumsum(x, axis=0). Unlike a sum reduction, this operation keeps one output for every input position.