Re: Does the order matter to add a sequence of floating numbers



In article <KpudnSua1py4xrranZ2dnUVZ8t2snZ2d@xxxxxx>,
Richard Heathfield <rjh@xxxxxxxxxxxxxxx> wrote:
JosephLee said:

Let's say float arr[100], we want to add them up, does the order
matter? what is the different between arr[0] +..+ arr[99], and
arr[99]+...+arr[0]?

You wouldn't think it would make a difference, would you? But it can,
nevertheless, especially when some or all of the values are near the
limits of what can be represented.

I tried fairly hard to write a program to demonstrate this, and failed. :-)

Is there a subtle joke I'm missing here ....

I just tried this myself, thinking maybe it was harder than it
seemed, especially if one adopted the constraint that the array
had to have exactly 100 elements. Below is what I came up with.
It does take the "else" branch at the end (different results).

#include <stdio.h>
#define SMALL 0.1f
#define LARGE 100.0f
#define COUNT 100
int main(void) {
float small_to_large = 0.0f;
float large_to_small = 0.0f;
float arr[COUNT];
int i;
arr[0] = LARGE;
for (i = 1; i < COUNT; ++i) {
arr[i] = SMALL;
}
for (i = 0; i < COUNT; ++i) {
large_to_small += arr[i];
}
for (i = COUNT-1; i >= 0; --i) {
small_to_large += arr[i];
}
if (small_to_large == large_to_small) {
fprintf(stdout, "same result: %14.10g\n", small_to_large);
}
else {
fprintf(stdout, "different results: %14.10g %14.10g\n",
small_to_large, large_to_small);
}
return 0;
}

--
B. L. Massingill
ObDisclaimer: I don't speak for my employers; they return the favor.
.



Relevant Pages

  • Re: Interesting code
    ... Richard Heathfield wrote: ... int sqrt ... function name choice invades implementation namespace, thus invoking ... value regardless, thus invoking undefined behaviour; ...
    (comp.lang.c)
  • Re: idiom related
    ... Richard Heathfield writes: ... Undefined behaviour if dest is not properly aligned for an int. ... Lets say an array of characters has ...
    (comp.lang.c)
  • Re: wits end
    ... Richard Heathfield writes: ... Or *pt = t (equivalent and, IMHO, clearer, since pt points to a single ... int, not an array). ...
    (comp.lang.c)
  • Re: Pointers in C
    ... Richard Heathfield wrote: ... reasons. ... int main ... My compiler is determined ...
    (comp.lang.c)
  • Re: union
    ... Richard Heathfield wrote: ... sizeof yields a size_t, not an int, so %d is not an appropriate printf ... format specifier for it. ...
    (comp.lang.c)