Talk About Network



Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C > Speaking of sum...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 1 Topic 26109 of 26198
Post > Topic >>

Speaking of sum programs (let's keep Razi out of it) here's my

by user923005 <dcorbit@[EMAIL PROTECTED] > May 7, 2008 at 01:46 PM

typedef struct KahanAdder_t {
    double sum_; /* The current working sum. */
    double carry_; /* The carry from the previous operation */
    double temp_; /* A temp used to capture residual bits of precision
*/
    double y_; /* A temp used to capture residual bits of precision */
} KahanAdder_t;

 /* After each add operation, the carry will contain the additional */
 /* bits that could be left out from the previous operation. */
void            add(const double datum, KahanAdder_t * kp)
{
    kp->y_ = datum - kp->carry_;
    kp->temp_ = kp->sum_ + kp->y_;
    kp->carry_ = (kp->temp_ - kp->sum_) - kp->y_;
    kp->sum_ = kp->temp_;
}

void reset( KahanAdder_t * kp)
{
    kp->y_ = 0;
    kp->temp_ = 0;
    kp->carry_ = 0;
    kp->sum_ = 0;
}

#define MAXLINELEN 256

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <float.h>
int             main(void)
{
    KahanAdder_t    k = {0};
    double          d;
    double          standard_sum = 0;
    float           standard_sum_f = 0;
    clock_t         start, end;
    unsigned        count = 0;
    char line[MAXLINELEN];

    setvbuf(stdin, NULL, _IOFBF, 1024 * 16);
    start = clock();
    while (fgets(line, sizeof line, stdin)) {
        d = atof(line);
        add(d, &k);
        standard_sum += d;
        standard_sum_f += (float) d;
        count++;
    }
    end = clock();

    printf("Standard sum (double) = %20.15f\n"
           "Kahan sum (double)    = %20.15f\n"
           "Standard sum (float)  = %20.15f\n"
           "Number of items was %u\n"
           "Time consumed was %f seconds\n",
           standard_sum,
           k.sum_,
           standard_sum_f,
           count,
           (end - start) * 1.0 / CLOCKS_PER_SEC
           );

    return 0;
}
/* Possible Output from a file of 5,000,001 numbers:
C:\tmp\Release> foo.exe < c:\tmp\n.txt
Standard sum (double) = 27104700.447471067000000
Kahan sum (double)    = 27104700.447473072000000
Standard sum (float)  = 26857582.000000000000000
Number of items was 5000001
Time consumed was 4.594000 seconds
*/




 1 Posts in Topic:
Speaking of sum programs (let's keep Razi out of it) here's my
user923005 <dcorbit@[E  2008-05-07 13:46:33 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Wed May 14 19:10:17 CDT 2008.