Re: Does the order matter to add a sequence of floating numbers
- From: blmblm@xxxxxxxxxxxxx <blmblm@xxxxxxxxxxxxx>
- Date: 30 Oct 2007 17:50:21 GMT
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.
.
- Follow-Ups:
- Re: Does the order matter to add a sequence of floating numbers
- From: Richard Heathfield
- Re: Does the order matter to add a sequence of floating numbers
- References:
- Does the order matter to add a sequence of floating numbers
- From: JosephLee
- Re: Does the order matter to add a sequence of floating numbers
- From: Richard Heathfield
- Does the order matter to add a sequence of floating numbers
- Prev by Date: Re: Does the order matter to add a sequence of floating numbers
- Next by Date: Re: Does the order matter to add a sequence of floating numbers
- Previous by thread: Re: Does the order matter to add a sequence of floating numbers
- Next by thread: Re: Does the order matter to add a sequence of floating numbers
- Index(es):
Relevant Pages
|