How best to sum up lots of floating point numbers?

205

Solution 1

For "more precise": this recipe in the Python Cookbook has summation algorithms which keep the full precision (by keeping track of the subtotals). Code is in Python but even if you don't know Python it's clear enough to adapt to any other language.

All the details are given in this paper.

Solution 2

See also: Kahan summation algorithm It does not require O(n) storage but only O(1).

Solution 3

There are many algorithms, depending on what you want. Usually they require keeping track of the partial sums. If you keep only the the sums x[k+1] - x[k], you get Kahan algorithm. If you keep track of all the partial sums (hence yielding O(n^2) algorithm), you get @dF 's answer.

Note that additionally to your problem, summing numbers of different signs is very problematic.

Now, there are simpler recipes than keeping track of all the partial sums:

  • Sort the numbers before summing, sum all the negatives and the positives independantly. If you have sorted numbers, fine, otherwise you have O(n log n) algorithm. Sum by increasing magnitude.
  • Sum by pairs, then pairs of pairs, etc.

Personal experience shows that you usually don't need fancier things than Kahan's method.

Share:
205
Henrique Amaral
Author by

Henrique Amaral

Updated on June 03, 2022

Comments

  • Henrique Amaral
    Henrique Amaral almost 2 years

    I am trying to receive a HTTP POST from Mirth Connect in my ASP.NET MVC solution but I don´t know how this data comes to my web application. I create a controller to receive it:

    public class IntegrationController : Controller
    {
    
        public ActionResult Index()
        {
            var c = HttpContext.CurrentHandler;
            var v = c.ToString();
            Console.Write("The value is" + v);
    
            return View();
        }
    }
    

    What should I receive in Index()? A dictionary? And once I receive it, how to how it in the viewer?

    Thank you.

    • Shyju
      Shyju over 7 years
      Create a C# class which can represent the data coming in and use that s the parameter. Model binder will be able to map the posted data(assuming it matches the naming requirements) and you can use parameter to pass data to view as needed.
  • Henrique Amaral
    Henrique Amaral over 7 years
    Hey @rboe. Yes, this works very good. I create a specific model in my folder Model to define the DataModel class. Does it make sense? I mean, from there I can for exemple store data in my database or show it in the View.