i was just testing maximum representation of float in c on mac pro. my program looks like this. And there are two types of program which increase by multiply and adding. #include
int main(void) {
float a;
a = 0;
int index = 0;
while(1) {
a++;
a = a +10000000000; // 1, **adding** **resulting (1)**
//a = a* 5; 2, **multiplying** **resulting (2)**
printf("%f, %d\n",a,idex);
}
}
Resulting (1) It kept increasing till certain point where it just display the same result looks like this 288230376151711744.000000.
Resulting (2) It didn't even show anything but inf
Could anyone explain why there is different situation happening ..?
Consider an example.
Assume that a float number uses decimal representation, a mantissa has only one decimal digit, an exponent is in a range 0-2. So, all possible numbers are 0, 1, 2, ..., 9, 10, 20, ..., 90, 100, 200, ..., 900
. For example, 12 is not possible number because two decimal digit is required (1 and 2). 1000 is not possible value because too much zeroes are placed at the end (3 zeroes at the end, but maximum is 2). And we have special inf
value to indicate overflow.
Let's try to increment and see what happens.
1 + 1 = 2, (ok) 2 + 1 = 3, (ok) ... 8 + 1 = 9, (ok) 9 + 1 = 10, (ok) 10 + 1 = 11 -> 10, (not enough space to safe two digits, result is rounded to nearest possible number, that is 10) 10 + 1 = 11 -> 10, (not enough space to safe two digits, result is rounded to nearest possible number, that is 10) ...
Let's try to multiply by 2 and see what happens:
1 * 2 = 2, (ok) 2 * 2 = 4, (ok) 4 * 2 = 8, (ok) 8 * 2 = 16 -> 20, (not enough space to safe two digits, result is rounded to nearest possible number, that is 20) 20 * 2 = 40, (ok) 40 * 2 = 80, (ok) 80 * 2 = 160 -> 200, (not enough space to safe two digits, result is rounded to nearest possible number, that is 200) 200 * 2 = 400, (ok) 400 * 2 = 800, (ok) 800 * 2 = 1600 -> inf, (overflow, the result is more that maximum value (900), so it is inf) inf * 2 = inf, (ok) inf * 2 = inf, (ok) ...