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



Richard Heathfield 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. :-)

How about:

#include <stdio.h>
#include <limits.h>

#define SIZE 10

int main(void) {
unsigned int val, va[SIZE], sum;
size_t i;

/* create array */
val = UINT_MAX / 8;
for (i = 0; i < SIZE; i++) va[i] = val + i;

sum = 0; i = 0;
while (va[i] < (INT_MAX - sum)) {
sum += va[i];
i++;
}
printf("Int overflow at i = %d with i increasing\n", (int)i);

sum = 0; i = SIZE - 1;
while (va[i] < (INT_MAX - sum)) {
sum += va[i];
i--;
}
printf("Int overflow at i = %d with i decreasing\n", (int)i);

return 0;
}

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>


--
Posted via a free Usenet account from http://www.teranews.com

.



Relevant Pages