Here’s an oddity (to me, at least). This routine prints true:
double x = 11.0;
double y = 10.0;
if (x-y == 1.0) {
// print true
} else {
// print false
}
But this routine prints false:
double x = 1.1;
double y = 1.0;
if (x-y == 0.1) {
// print true
} else {
// print false
}
Anyone care to explain what’s going on here? I’m guessing it has something to do with integer arithmetic for ints posing as floats. Also, are there other bases (other than 10) that have this property?
1.0 has an exact binary representation. 0.1 does not.
perhaps you are asking why 0.1 is not stored as a mantissa of 1 and an exponent of -10? but that’s not how it works. it’s not a decimal number plus an exponent, but a binary number. so “times 10” is not a natural thing.
sorry, maybe the last part is unclear. it’s better to think of the exponent as a shift of bits. no shift of bits will convert an infinite sequence like 0.1 (decimal) into a finite one.