Can a set of floating point numbers be above average?

I am dealing with code that essentially boils down to the following:

float child[24];
// assume child[] is filled here with some values
float sum = 0;
float avg;
for (int i = 0; i < 24; i++)
  sum += child[i];
avg = sum / 24;

int n_above_avg = 0;
int n_below_avg = 0;
for (int i = 0; i < 24; i++)
  if (child[i] <= avg)
    n_below_avg++;
  else
    n_above_avg++;

Due to floating point inaccuracies, is it possible at the end of this code to n_below_avgbe equal to 0? Suppose that an overflow cannot occur, and that all programmers look beautiful.

+4
source share
3 answers

In the calculation avgthat you use, it is technically possible for all elements of the float array to be higher avg.

, v , avg v, , avg.

v, , - , , 23 24 . , , , , , .

. Python. , . avg , , .

+7

64- 0 :

void ff() {
    float child[24];
    float sum = 0;
    float avg;

    for (int i = 0; i < 24; i++)
        child[i] = 0.717297;
    for (int i = 0; i < 24; i++)
        sum += child[i];
    avg = sum / 24; 
    int n_above_avg = 0;
    int n_below_avg = 0;
    for (int i = 0; i < 24; i++)
        if (child[i] <= avg)
            n_below_avg++;
        else
            n_above_avg++;
    printf("%d\n", n_below_avg);
}

( ): 0.108809 0.891529 0.931835 0.738534 0.354049 0.829201 0.893372 0.858676 0.920128 0.447034 0.187533 0.732149

+3

, , : child nan, avg , child[i] <= avg ( nan ).

+2

All Articles