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
38
votes
2 answers

How to calculate sum of a DataTable's Column in LINQ (to Dataset)?

I'm just started to read up on LINQ and I want to start incorporating it into my code. I know how to compute the sum of a DataTable's column by either "Foreach"-ing through the rows or by doing a compute.sum on the specific column. How do I do the…
rivera.reyrivera
  • 383
  • 1
  • 3
  • 5
38
votes
2 answers

Aggregate vs Sum Performance in LINQ

Three different implementations of finding the sum of an IEnumerable < int> source are given below along with the time taken when the source has 10,000 integers. source.Aggregate(0, (result, element) => result + element); takes 3 ms source.Sum(c…
Gopal
  • 1,372
  • 2
  • 16
  • 32
37
votes
7 answers

python's sum() and non-integer values

Is there a simple and quick way to use sum() with non-integer values? So I can use it like this: class Foo(object): def __init__(self,bar) self.bar=bar mylist=[Foo(3),Foo(34),Foo(63),200] result=sum(mylist) # result should be 300 I…
sloth
  • 99,095
  • 21
  • 171
  • 219
36
votes
3 answers

How to merge two arrays by summing the merged values

Possible Duplicate: PHP: How to sum values of the array of the same key I am looking for an array_merge() function that does NOT replace values, but ADDS them. Example, this is the code I am trying: echo "
"; 

    $a1 = array(
        …
Erick
  • 369
  • 1
  • 3
  • 4
34
votes
4 answers

Difference between np.dot and np.multiply with np.sum in binary cross-entropy loss calculation

I have tried the following code but didn't find the difference between np.dot and np.multiply with np.sum Here is np.dot code logprobs = np.dot(Y, (np.log(A2)).T) + np.dot((1.0-Y),(np.log(1 - A2)).T) print(logprobs.shape) print(logprobs) cost =…
Asad Shakeel
  • 1,949
  • 1
  • 23
  • 29
34
votes
6 answers

Finding a sum in nested list using a lambda function

I have a data structure similar to this table = [ ("marley", "5"), ("bob", "99"), ("another name", "3") ] What I would like to do, to get the sum of the 2nd column (5 + 99 + 3) functionally like this: total = sum(table, lambda tup :…
hlin117
  • 20,764
  • 31
  • 72
  • 93
34
votes
6 answers

Using SUM() without grouping the results

I already read (this), but couldn't figure out a way to implement it to my specific problem. I know SUM() is an aggregate function and it doesn't make sense not to use it as such, but in this specific case, I have to SUM() all of the results while…
Anonymous
  • 3,679
  • 6
  • 29
  • 40
33
votes
12 answers

How to avoid floating point precision errors with floats or doubles in Java?

I have a very annoying problem with long sums of floats or doubles in Java. Basically the idea is that if I execute: for ( float value = 0.0f; value < 1.0f; value += 0.1f ) System.out.println( value ); What I get…
tunnuz
  • 23,338
  • 31
  • 90
  • 128
33
votes
6 answers

Percentage from Total SUM after GROUP BY SQL Server

I have these results: PersonID SUM(PA.Total) ------------------------- 1 75 2 75 3 15 4 15 5 60 6 60 With the table like: PersonID Total ------------------ …
Ryan Gadsdon
  • 2,272
  • 4
  • 31
  • 56
31
votes
5 answers

Efficient summation in Python

I am trying to efficiently compute a summation of a summation in Python: WolframAlpha is able to compute it too a high n value: sum of sum. I have two approaches: a for loop method and an np.sum method. I thought the np.sum approach would be…
Adam
  • 433
  • 5
  • 9
31
votes
13 answers

Get the sum of all digits in a numeric string

How do I find the sum of all the digits in a number in PHP?
Leticia Meyere
  • 319
  • 1
  • 3
  • 3
31
votes
4 answers

Avg of a Sum in one query

I would like to know if I can get the average of a sum in one single SQL SERVER request, Have tried to do it with the following request but it doesn't work: SELECT t.client, AVG(SUM(t.asset)) AS Expr1 FROM TABLE t GROUP BY t.client
Roch
  • 21,741
  • 29
  • 77
  • 120
29
votes
6 answers

Improve the speed of a JavaScript function

I have a task I found on CodeWars and I managed to solve it, however, after submitting is says: Execution timed out: (12000 ms) When I try to test the function is passed, but I guess it is too slow. Before you condemn me for not finding the answer…
Cortoloman
  • 695
  • 1
  • 7
  • 14
29
votes
5 answers

Algorithm to find the maximum sum in a sequence of overlapping intervals

The problem I am trying to solve has a list of intervals on the number line, each with a pre-defined score. I need to return the maximum possible total score. The catch is that the intervals overlap, and of the overlapping intervals I can use only…
efficiencyIsBliss
  • 3,043
  • 7
  • 38
  • 44
29
votes
2 answers

Sum values of a single row?

I have a MySQL query that returns a single row that is a series of 1s and 0s. It's for a progress bar indicator. I have the summing of it in code now, but I tried to sum the values in a query, and realized I couldn't use SUM(), because they're many…
user151841
  • 17,377
  • 29
  • 109
  • 171