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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • user923005

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

    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("Standar d 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\Releasef oo.exe < c:\tmp\n.txt
    Standard sum (double) = 27104700.447471 067000000
    Kahan sum (double) = 27104700.447473 072000000
    Standard sum (float) = 26857582.000000 000000000
    Number of items was 5000001
    Time consumed was 4.594000 seconds
    */


Working...