Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the cumulative sum for a vector of doubles in C++?

I have a vector of doubles and I need to create another array which is a cumulative sum of the elements of the first. For example;

 vector<double> Array(10,1);
 vector<double> Sum(10);  

 Sum[0] = Array[0]; 
 for(unsigned int i=1; i<Array.size(); i++)
     Sum[i] = Sum[i-1] + Array[i]; 

Is there an in-built function that will perform the above cumulative sum?

like image 642
Wawel100 Avatar asked Jul 20 '10 09:07

Wawel100


People also ask

What is cumulative sum example?

The definition of the cumulative sum is the sum of a given sequence that is increasing or getting bigger with more additions. The real example of a cumulative sum is the increasing amount of water in a swing pool. Example: Input: 10, 15, 20, 25, 30. Output: 10, 25, 45, 70, 100.

What is cumulative summation?

Cumulative sums, or running totals, are used to display the total sum of data as it grows with time (or any other series or progression). This lets you view the total contribution so far of a given measure against time.

Is cumulative same as sum?

A running total in Excel (also known as cumulative sum) refers to the partial sum of a data set. It is a summation of a sequence of numbers that is refreshed every time a new number is added to the sequence.


1 Answers

Without having tested it, something like

std::partial_sum(Array.begin(), Array.end(), Sum.begin(), plus<double>());

should do the trick, if it's C++. (Actually, the plus<double>() can be defaulted out, it seems.)

like image 143
Pontus Gagge Avatar answered Sep 30 '22 18:09

Pontus Gagge