...
This noncompliant code example takes the mean of 10 identical numbers and checks to see if the mean matches this number. It should because the ten numbers are all 10.1
. Yet, because of the imprecision of floating-point arithmetic, the computed mean does not match this number.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> /* Returns the mean value of the array */ float mean(float array[], int size) { float total = 0.0; size_t i; for (i = 0; i < size; i++) { total += array[i]; printf("array[%d] = %f and total is %f\n", i, array[i], total); } if (size != 0) return total / size; else return 0.0; } enum { array_size = 10 }; float array_value = 10.1; int main(void) { float array[array_size]; float avg; size_t i; for (i = 0; i < array_size; i++) { array[i] = array_value; } avg = mean( -array, array_size); printf("mean is %f\n", avg); if (avg == array[0]) { printf("array[0] is the mean\n"); } else { printf("array[0] is not the mean\n"); } return 0; } |
...
This code may be fixed by replacing the floating-point numbers with integers for the internal additions. Floats are used only when printing results and when doing the division to compute the mean.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> /* Returns the mean value of the array */ float mean(int array[], int size) { int total = 0; size_t i; for (i = 0; i < size; i++) { total += array[i]; printf("array[%d] = %f and total is %f\n", i, array[i] / 100.0, total / 100.0); } if (size != 0) return ((float) total) / size; else return 0.0; } enum {array_size = 10}; int array_value = 1010; int main(void) { int array[array_size]; float avg; size_t i; for (i = 0; i < array_size; i++) { array[i] = array_value; } avg = mean(array, array_size); printf("mean is %f\n", avg / 100.0); if (avg == array[0]) { printf("array[0] is the mean\n"); } else { printf("array[0] is not the mean\n"); } return 0; } |
...