The Wayback Machine - https://web.archive.org/web/20240727120117/https://www.geeksforgeeks.org/kahan-summation-algorithm/
Open In App

Kahan Summation Algorithm

Last Updated : 25 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Prerequisites: Rounding off errors, Introduction to the floating-point representation
Kahan summation algorithm, also known as compensated summation and summation with the carry algorithm, is used to minimize the loss of significance in the total result obtained by adding a sequence of finite-precision floating-point numbers. This is done by keeping a separate running compensation (a variable to accumulate small errors). 

Reason for Loss of Significance: 

  • As we know in Java language we have two primitive floating-point types, float and double, with single-precision 32-bit and double-precision 64-bit format values and operations specified by IEEE 754. That is, they are represented in a form like:
SIGN FRACTION * 2EXP
  • For example, 0.15625 = (0.00101)2, which in floating-point format is represented as: 1.01 * 2-3. However, not all fractions can be represented exactly as a fraction of a power of two. For example, 0.1 = (0.000110011001100110011001100110011001100110011001100110011001… )2 and thus cannot be stored inside a floating-point variable.
  • Therefore, floating-point error/loss of significance refers to when a number that cannot be stored as it is in the IEEE floating-point representation and repetitively some arithmetic operation is performed on it. This leads to some unexpected value and the difference between the expected and the obtained value is the error.

Below is an implementation that simulates the significance error:

C++




// C++ program to illustrate the
// floating-point error
#include<bits/stdc++.h>
using namespace std;
 
double floatError(double no)
{
    double sum = 0.0;
    for(int i = 0; i < 10; i++)
    {
        sum = sum + no;
    }
    return sum;
}
 
// Driver code
int main()
{
    cout << setprecision(16);
    cout << floatError(0.1);
}
 
// This code is contributed by rutvik_56


Java




// Java program to illustrate the
// floating-point error
 
public class GFG {
 
    public static double floatError(double no)
    {
        double sum = 0.0;
        for (int i = 0; i < 10; i++) {
            sum = sum + no;
        }
        return sum;
    }
 
    public static void main(String[] args)
    {
 
        System.out.println(floatError(0.1));
    }
}


Python3




# Python3 program to illustrate the
# floating-point error
 
def floatError(no):
    sum = 0.0
    for i in range(10):
        sum = sum + no
    return sum
 
if __name__ == '__main__':
    print(floatError(0.1))
 
# This code is contributed by mohit kumar 29


C#




// C++ program to illustrate the
// floating-point error
using System;
 
public class Program
{
    public static double FloatError(double no)
    {
        double sum = 0.0;
        for (int i = 0; i < 10; i++)
        {
            sum += no;
        }
        return Math.Round(sum - 1E-15, 15);
    }
 
  // Driver code
    public static void Main()
    {
        Console.WriteLine($"{FloatError(0.1):F15}");
    }
}


Javascript




<script>
// Javascript program to illustrate the
// floating-point error
 
function floatError(no)
{
    let sum = 0.0;
        for (let i = 0; i < 10; i++) {
            sum = sum + no;
        }
        return sum;
}
 
document.write(floatError(0.1));
 
 
 
// This code is contributed by patel2127
</script>


Output

0.9999999999999999

Note: The expected value for the above implementation is 1.0 but the value returned is 0.9999999999999999. Therefore, in this article, a method to reduce this error by using Kahan’s Summation algorithm is discussed. 

Kahan Summation Algorithm: The idea of the Kahan summation algorithm is to compensate for the floating-point error by keeping a separate variable to store the running time errors as the arithmetic operations are being performed. This can be visualised by the following pseudocode: 

function KahanSum(input)
    var sum = 0.0                    
    var c = 0.0                      
    for i = 1 to input.length do     
                                     
        var y = input[i] - c         
        var t = sum + y              
        c = (t - sum) - y            
                                     
        sum = t                      
                                     
    next i                          

    return sum

In the above pseudocode, algebraically, the variable c in which the error is stored is always 0. However, when there is a loss of significance, it stores the error in it. 

Below is the implementation of the above approach:

C++




// C++ program to illustrate the
// Kahan summation algorithm 
#include <bits/stdc++.h>
using namespace std;
 
// Function to implement the Kahan
// summation algorithm
double kahanSum(vector<double> &fa;)
{
    double sum = 0.0;
 
    // Variable to store the error
    double c = 0.0;
 
    // Loop to iterate over the array
    for(double f : fa)
    {
        double y = f - c;
        double t = sum + y;
         
        // Algebraically, c is always 0
        // when t is replaced by its
        // value from the above expression.
        // But, when there is a loss,
        // the higher-order y is cancelled
        // out by subtracting y from c and
        // all that remains is the
        // lower-order error in c
        c = (t - sum) - y;
        sum = t;
    }
    return sum;
}
 
// Function to implement the sum
// of an array
double sum(vector<double> &fa;)
{
    double sum = 0.0;
 
    // Loop to find the sum of the array
    for(double f : fa)
    {
        sum = sum + f;
    }
    return sum;
}
 
// Driver code
int main()
{
    vector<double> no(10);
    for(int i = 0; i < 10; i++)
    {
        no[i] = 0.1;
    }
  
    // Comparing the results
      cout << setprecision(16);
    cout << "Normal sum: " << sum(no) << " \n";
    cout << "Kahan sum: " << kahanSum(no);    
}
 
// This code is contributed by ajaykr00kj


Java




// Java program to illustrate the
// Kahan summation algorithm
 
public class GFG {
 
    // Function to implement the Kahan
    // summation algorithm
    private static double kahanSum(double... fa)
    {
        double sum = 0.0;
 
        // Variable to store the error
        double c = 0.0;
 
        // Loop to iterate over the array
        for (double f : fa) {
 
            double y = f - c;
            double t = sum + y;
 
            // Algebraically, c is always 0
            // when t is replaced by its
            // value from the above expression.
            // But, when there is a loss,
            // the higher-order y is cancelled
            // out by subtracting y from c and
            // all that remains is the
            // lower-order error in c
            c = (t - sum) - y;
 
            sum = t;
        }
 
        return sum;
    }
 
    // Function to implement the sum
    // of an array
    private static double sum(double... fa)
    {
        double sum = 0.0;
 
        // Loop to find the sum of the array
        for (double f : fa) {
            sum = sum + f;
        }
 
        return sum;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        double[] no = new double[10];
        for (int i = 0; i < no.length; i++) {
            no[i] = 0.1;
        }
 
        // Comparing the results
        System.out.println("Normal sum: " + sum(no));
        System.out.println("Kahan sum: " + kahanSum(no));
    }
}


Javascript




<script>
 
// Javascript program to illustrate the
// Kahan summation algorithm
 
// Function to implement the Kahan
// summation algorithm
function kahanSum(fa)
{
    let sum = 0.0;
  
    // Variable to store the error
    let c = 0.0;
 
    // Loop to iterate over the array
    for(let f = 0; f < fa.length; f++)
    {
        let y = fa[f] - c;
        let t = sum + y;
 
        // Algebraically, c is always 0
        // when t is replaced by its
        // value from the above expression.
        // But, when there is a loss,
        // the higher-order y is cancelled
        // out by subtracting y from c and
        // all that remains is the
        // lower-order error in c
        c = (t - sum) - y;
 
        sum = t;
    }
    return sum;
}
 
// Function to implement the sum
// of an array
function sum(fa)
{
    let sum = 0.0;
  
    // Loop to find the sum of the array
    for(let f = 0; f < fa.length; f++)
    {
        sum = sum + fa[f];
    }
    return sum;
}
 
// Driver code
let no = new Array(10);
for(let i = 0; i < no.length; i++)
{
    no[i] = 0.1;
}
 
// Comparing the results
document.write("Normal sum: " +
               sum(no) + "<br>");
document.write("Kahan sum: " +
               kahanSum(no).toFixed(1) + "<br>");
 
// This code is contributed by unknown2108
 
</script>


Python3




# Python3 program to illustrate the
# Kahan summation algorithm
 
# Function to implement the Kahan
# summation algorithm
def kahanSum(fa):
    sum = 0.0
 
    # Variable to store the error
    c = 0.0
 
    # Loop to iterate over the array
    for f in fa:
        y = f - c
        t = sum + y
 
        # Algebraically, c is always 0
        # when t is replaced by its
        # value from the above expression.
        # But, when there is a loss,
        # the higher-order y is cancelled
        # out by subtracting y from c and
        # all that remains is the
        # lower-order error in c
        c = (t - sum) - y
        sum = t
 
    return sum
 
 
# Driver code
if __name__ == "__main__":
    no = [0.0] * 10
    for i in range(10):
        no[i] = 0.1
 
    # Comparing the results
    print("Normal sum: ", sum(no))
    print("Kahan sum: ", kahanSum(no))


C#




// Python3 program to illustrate the
// Kahan summation algorithm
 
// Function to implement the Kahan
// summation algorithm
using System;
 
class Program {
    // Driver code
    static void Main(string[] args) {
        double[] no = new double[10];
        for (int i = 0; i < 10; i++) {
            no[i] = 0.1;
        }
        // Comparing the results
        Console.WriteLine("Normal sum: {0}", Sum(no));
        Console.WriteLine("Kahan sum: {0}", KahanSum(no));
    }
 
    static double Sum(double[] fa) {
        double sum = 0.0;
 
        foreach (double f in fa) {
            sum += f;
        }
 
        return sum;
    }
 
    static double KahanSum(double[] fa) {
        double sum = 0.0;
         
        // Variable to store the error
        double c = 0.0;
 
        foreach (double f in fa) {
            double y = f - c;
            double t = sum + y;
             
            // Algebraically, c is always 0
            // when t is replaced by its
            // value from the above expression.
            // But, when there is a loss,
            // the higher-order y is cancelled
            // out by subtracting y from c and
            // all that remains is the
            // lower-order error in c
            c = (t - sum) - y;
            sum = t;
        }
 
        return sum;
    }
}
 
// This code is contributed by Shiv1043g


Output: 

Normal sum: 0.9999999999999999
Kahan sum: 1.0

 

Time Complexity: O(N), where N is the length of the list.
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Difference between the summation of numbers whose frequency of all digits are same and different
Given an array of N integers, find the difference between the summation of numbers whose frequency of all digits are same and different. For e.g. 8844, 1001, 56, 77, 34764673 are the examples of numbers where all digits have the same frequency. Similarly, 545, 44199, 76672, 202 are the examples of numbers whose frequency of digits are not the same.
7 min read
Maximize the summation of numbers in a maximum of K moves in range [L, R]
Given an array arr[] of N integers and Q queries. Each query consists of 3 integers L, R and K. You can move from index i to index i + 1 in a single step or stay in that particular index in a single step. You can move from L to R index in a maximum of K steps and print the summation of every number you were at in every step including the L-th numbe
15 min read
Series summation if T(n) is given and n is very large
Given a sequence whose nth term is T(n) = n2 - (n - 1)2 The task is to evaluate the sum of first n terms i.e. S(n) = T(1) + T(2) + T(3) + ... + T(n) Print S(n) mod (109 + 7).Examples: Input: n = 3 Output: 9 S(3) = T(1) + T(2) + T(3) = (12 - 02) + (22 - 12) + (32 - 22) = 1 + 3 + 5 = 9Input: n = 10 Output: 100 Approach: If we try to find out some ini
3 min read
Check if summation of two words is equal to target word
Given three strings A, B, and C of size L, M, and N respectively and consisting of only lower case English alphabets less than 'K'. The task is to check if the sum of strings A and B is equal to the string C after decoding the strings into integers by mapping alphabets with their index value in the list of alphabets and concatenating them. Examples
9 min read
Find the summation of the product of Array elements in range [L, R]
Given an array arr[] and two integers L and R. The task is to find the sum of the product of all the pairs (i, j) in the range [L, R], such that i ≤ j. Input: arr[] = { 1, 3, 5, 8 }, L = 0, R = 2Output: 58Explanation: As 1*1 + 1*3 + 1*5 + 3*3 + 3*5 + 5*5 = 58 Input: arr[] = { 2, 1, 4, 5, 3, 2, 1 }, L = 1, R = 5Output: 140 Naive Approach: The brute
8 min read
Difference summation with Array index matching
Given two sorted arrays A and B of size N and M respectively, the task is to find the value V, which is the summation of (A[j] - A[i]) for all pairs of i and j such that (j - i) is present in array B. Examples: Input: N = 4, M = 2, A[] = {1, 2, 3, 4}, B[] = {1, 3}Output: 6Explanation: Valid pairs of (i, j) are (1, 2), (2, 3), (3, 4), (1, 4). So the
7 min read
Minimum possible value of Summation of |A[i] - A[i+K]|
Given an array arr[] of N integers and an integer K, the task is to find the minimum possible value of summation of |A[i] - A[i+K]| for any permutation of array arr[] (for all the indices from 0 to N - K - 1) Examples: Input: N = 4, arr = {1, 2, 3, 4}, K = 2Output: 2Explanation: For the permutation {1, 3, 2, 4}, for i = 0 the value of | A[0] - A[2]
7 min read
Summation of Alphanumeric Strings
Just like our number system where we have 10 digits starting from 0 to 9, Geek has created a custom numerical system where he has 36 digits which are 0 to 9 then A to Z where '0' is the smallest, and 'Z' is the largest number, which follows their respective order (Similar to Hexadecimal number system till F). Your task is to calculate the sum of th
11 min read
Summed Area Table - Submatrix Summation
Given a matrix of size M x N, there are large number of queries to find submatrix sums. Inputs to queries are left top and right bottom indexes of submatrix whose sum is to find out. How to preprocess the matrix so that submatrix sum queries can be performed in O(1) time. Example: tli : Row number of top left of query submatrix tlj : Column number
2 min read
Summation of GCD of all the pairs up to N
Given a number N, find sum of all GCDs that can be formed by selecting all the pairs from 1 to N. Examples: Input : 4 Output : 7 Explanation: Numbers from 1 to 4 are: 1, 2, 3, 4 Result = gcd(1,2) + gcd(1,3) + gcd(1,4) + gcd(2,3) + gcd(2,4) + gcd(3,4) = 1 + 1 + 1 + 1 + 2 + 1 = 7 Input : 12 Output : 105 Input : 1 Output : 0 Input : 2 Output : 1 A Nai
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg