this question has answer here:
- is floating point math broken? 20 answers
consider following program:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { int i; long int rr; double dd; double arr[10] = {55.550,55.551,55.552,55.553,55.554,55.555,55.556,55.557,55.558,55.559}; printf("\n\ntest1"); for(i=0;i<10;i++) { dd = 100 * arr[i]; rr = (long int)dd; printf("\n 100 * %10.4lf == %10.4lf >>>>> %ld",arr[i], dd, rr); } printf("\n\ntest2"); for(i=0;i<10;i++) { printf("\n 100 * %10.4lf == %10.4lf >>>>> %ld", arr[i], 100 * arr[i], (long int)(100 * arr[i])); } return 0; } after execute thing got:
test1 100 * 55.5500 == 5555.0000 >>>>> 5555 100 * 55.5510 == 5555.1000 >>>>> 5555 100 * 55.5520 == 5555.2000 >>>>> 5555 100 * 55.5530 == 5555.3000 >>>>> 5555 100 * 55.5540 == 5555.4000 >>>>> 5555 100 * 55.5550 == 5555.5000 >>>>> 5555 100 * 55.5560 == 5555.6000 >>>>> 5555 100 * 55.5570 == 5555.7000 >>>>> 5555 100 * 55.5580 == 5555.8000 >>>>> 5555 100 * 55.5590 == 5555.9000 >>>>> 5555 test2 100 * 55.5500 == 5555.0000 >>>>> 5554 <-- @ here ! 100 * 55.5510 == 5555.1000 >>>>> 5555 100 * 55.5520 == 5555.2000 >>>>> 5555 100 * 55.5530 == 5555.3000 >>>>> 5555 100 * 55.5540 == 5555.4000 >>>>> 5555 100 * 55.5550 == 5555.5000 >>>>> 5555 100 * 55.5560 == 5555.6000 >>>>> 5555 100 * 55.5570 == 5555.7000 >>>>> 5555 100 * 55.5580 == 5555.8000 >>>>> 5555 100 * 55.5590 == 5555.9000 >>>>> 5555 process returned 0 (0x0) execution time : -0.000 s press key continue. seems when multiply , cast 55.550 last digit missed. normal ?
how casting should preceded in case ?
it standard problem of float precision. value of 55.550 can not stored in memory exactly, different close value stored. different sequences of operations (including storing intermediate results double) can affect outcome. may on first test, value in dd becomes 5555, while in second case 100 * arr[i] becomes, say, 5554.9999999997.
Comments
Post a Comment