Questions tagged [sum]

The result of adding two or more quantities together.

The sum or total refers to the result of a summation operation. To refer to the operation yields a sum, use the [tag: addition] tag. A summation involves adding two or more numbers or other quantities. It is primarily an arithmetic operation which means it deals with numbers and also other mathematical objects. However, sum can be used in other contexts which may not necessarily be a result of a mathematical operation. Almost all programming languages support addition of numbers using the + operator. Most programming languages support the summation operation through a built-in language construct or as a utility function part of the standard library.


Examples of sum in various programming languages

C++

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> array{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int sum = std::accumulate(array.begin(), array.end(), 0, std::plus<int>());
    std::cout << sum;
    return 0;
}

Python:

sum_of_items = sum([1, 2, 3, 4, 5, 6])
# sum_of_items will be equal to 21

SQL

SELECT SUM(column1) FROM MyTable
WHERE column1 = "condition"

C#

List<int> array = new List<int>() {1, 2, 3, 4, 5};
int sum = array.Sum();  # sum == 21

Java

import java.util.Arrays;
public class MyClass {
    public static void main(String args[]) {
      var numbers = Arrays.asList(1, 2, 3, 4, 5);
      var sum = numbers.stream().mapToInt(Integer::intValue).sum();
      System.out.println(sum);
    }
}

R

x <- c(1.1, 2.5, -0.4)
y <- c(NA, 1.7)
sum(x)
sum(y)
sum(y, na.rm = TRUE)
sum(x, y)  ## as same as sum(c(x, y))
sum(x, y, na.rm = TRUE)  ## as same as sum(c(x, y), na.rm = TRUE)
15351 questions
61
votes
2 answers

In numpy.sum() there is parameter called "keepdims". What does it do?

In numpy.sum() there is parameter called keepdims. What does it do? As you can see here in the documentation: http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html numpy.sum(a, axis=None, dtype=None, out=None,…
Ney J Torres
  • 1,611
  • 3
  • 12
  • 14
61
votes
8 answers

Python sum, why not strings?

Python has a built in function sum, which is effectively equivalent to: def sum2(iterable, start=0): return start + reduce(operator.add, iterable) for all types of parameters except strings. It works for numbers and lists, for example: …
Muhammad Alkarouri
  • 23,884
  • 19
  • 66
  • 101
60
votes
7 answers

SQL Update to the SUM of its joined values

I'm trying to update a field in the database to the sum of its joined values: UPDATE P SET extrasPrice = SUM(E.price) FROM dbo.BookingPitchExtras AS E INNER JOIN dbo.BookingPitches AS P ON E.pitchID = P.ID AND P.bookingID = 1 WHERE E.[required]…
Mark Clancy
  • 7,831
  • 8
  • 43
  • 49
59
votes
9 answers

PySpark - Sum a column in dataframe and return results as int

I have a pyspark dataframe with a column of numbers. I need to sum that column and then have the result return as an int in a python variable. df = spark.createDataFrame([("A", 20), ("B", 30), ("D", 80)],["Letter", "Number"]) I do the following to…
Bryce Ramgovind
  • 3,127
  • 10
  • 41
  • 72
58
votes
5 answers

Why is a `for` loop so much faster to count True values?

I recently answered a question on a sister site which asked for a function that counts all even digits of a number. One of the other answers contained two functions (which turned out to be the fastest, so far): def count_even_digits_spyr03_for(n): …
Graipher
  • 6,891
  • 27
  • 47
57
votes
2 answers

What's the best way to sum all values in a Pandas dataframe?

I figured out these two methods. Is there a better one? >>> import pandas as pd >>> df = pd.DataFrame({'A': [5, 6, 7], 'B': [7, 8, 9]}) >>> print df.sum().sum() 42 >>> print df.values.sum() 42 Just want to make sure I'm not missing something more…
Bill
  • 10,323
  • 10
  • 62
  • 85
57
votes
8 answers

MYSQL sum() for distinct rows

I'm looking for help using sum() in my SQL query: SELECT links.id, count(DISTINCT stats.id) as clicks, count(DISTINCT conversions.id) as conversions, sum(conversions.value) as conversion_value FROM links LEFT OUTER JOIN…
makeee
  • 2,765
  • 5
  • 35
  • 42
56
votes
8 answers

Sum a list which contains 'None' using Python

Basically my question is say you have an list containing 'None' how would you try retrieving the sum of the list. Below is an example I tried which doesn't work and I get the error: TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'.…
Sam
  • 1,479
  • 3
  • 14
  • 16
56
votes
7 answers

How to sum properties of the objects within an array in Ruby

I understand that in order to sum array elements in Ruby one can use the inject method, i.e. array = [1,2,3,4,5]; puts array.inject(0, &:+) But how do I sum the properties of objects within an object array e.g.? There's an array of objects and…
Spike Fitsch
  • 747
  • 1
  • 7
  • 12
53
votes
9 answers

Getting N random numbers whose sum is M

I want to get N random numbers whose sum is a value. For example, let's suppose I want 5 random numbers that sum to 1. Then, a valid possibility is: 0.2 0.2 0.2 0.2 0.2 Another possibility is: 0.8 0.1 0.03 0.03 0.04 And so on. I need this for the…
marionmaiden
  • 3,250
  • 8
  • 33
  • 50
53
votes
8 answers

Sum all the elements java arraylist

If I had: ArrayList m = new ArrayList(); with the double values ​​inside, how should I do to add up all the ArrayList elements? public double incassoMargherita() { double sum = 0; for(int i = 0; i < m.size(); i++) { } …
user2324946
51
votes
6 answers

Disk usage of files whose names match a regex, in Linux?

So, in many situations I wanted a way to know how much of my disk space is used by what, so I know what to get rid of, convert to another format, store elsewhere (such as data DVDs), move to another partition, etc. In this case I'm looking at a…
Camilo Martin
  • 37,236
  • 20
  • 111
  • 154
51
votes
11 answers

Sum values from an array of key-value pairs in JavaScript

I have defined a JavaScript variables called myData which is a new Array like this: var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0], ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], …
Daniela costina Vaduva
  • 1,857
  • 5
  • 20
  • 22
48
votes
3 answers

Calculate average of column from MYSQL query

I've got a table that I am trying to calculate the average of the values in a column. Here is my lookup: SELECT SUM(P1_Score) AS value_sum FROM tblMatches Where P1_ID LIKE $playerID Any idea how I can determine the average (sum of values / total…
DoubleA
  • 736
  • 1
  • 7
  • 23
47
votes
3 answers

MySQL sum elements of a column

I have a table with 3 columns (A,B,C). I want to select some rows from the table and then the MySQL to return a single row having the values added on each column. A B C 1. 2 2 2 2. 4 4 4 3. 6 7 8 MySQL should return in this case, if I select all…
XCS
  • 27,244
  • 26
  • 101
  • 151