Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Summation function to minimize rounding issues

  1. Apr 29, 2013 #1

    rcgldr

    User Avatar
    Homework Helper

    This is a C++ class to be used for summation of doubles (floating point). It uses an array of 2048 doubles indexed by exponent to minimize rounding errors by only adding numbers that have the same exponent.

    NUM::NUM - array is cleared out when an instance of NUM is created
    NUM::clear() - clears out the array
    NUM::addnum() - add a number to the array
    NUM::getsum() - returns the current sum of the array

    link to zip of source file with example test code that adds 1./5. 4,294,967,295 (2^32-1) times and displays a sum using normal addition and using the SUM class.

    http://rcgldr.net/misc/sum.zip

    This is the key part of the SUM class, the addnum() function:

    Code (Text):

    void SUM::addnum(double d)      // add a number into the array
    {
    size_t i;

        while(1){
    //      i = exponent of d
            i = ((size_t)((*(unsigned long long *)&d)>>52))&0x7ff;
            if(i == 0x7ff){ // max exponent, could be overflow
                asum[i] += d;
                return;
            }
            if(this->asum[i] == 0){ // if empty slot store d
                asum[i] = d;
                return;
            }
            d += asum[i];           // else add slot to d, clear slot
            asum[i] = 0.;           // and continue until empty slot
        }
    }
     
     
  2. jcsd
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Can you offer guidance or do you also need help?
Draft saved Draft deleted



Similar Discussions: Summation function to minimize rounding issues
  1. Ifstream issues (Replies: 8)

  2. Rounding in C (Replies: 7)

  3. Strmm Issue (Replies: 1)

Loading...