Home >Backend Development >C++ >Can All Integer Values be Perfectly Represented as Doubles?
Are All Integer Values Perfectly Represented as Doubles?
The question arises as to whether all integer values are guaranteed to have a perfect representation as double-precision floating-point numbers. To answer this, we first delve into the representation of doubles.
Doubles are represented as mantissa * 2^exponent, where the mantissa includes fractional digits. This allows for the representation of both integer and decimal values.
Representation of 32-Bit Integers
For 32-bit integers, there are up to 53 bits available for the mantissa. This is sufficient to represent all possible 32-bit integers without fractional loss. Thus, yes, all 32-bit integer values are perfectly represented as doubles.
Representation of 64-Bit Integers
However, for 64-bit integers, the situation is different. IEEE 754 double-precision can guarantee perfect representation for up to 53 bits. Beyond that, there may be rounding errors. Therefore, no, not all 64-bit integer values are perfectly represented as doubles.
Empirically Verifying the Behavior
The following code snippet tests the conversion of integers to doubles:
<code class="cpp">#include <iostream> #include <limits> using namespace std; int main() { double test; volatile int test_int; for (int i = 0; i < numeric_limits<int>::max(); i++) { test = i; test_int = test; if (test_int != i) cout << "found integer i=" << i << ", test=" << test << endl; } return 0; }</code>
Running this code reveals that there are no integer values with fractional conversion errors for 32-bit integers. However, for 64-bit integers, it is possible to find integer values that convert to doubles with fractional differences and round back to the original integer value.
Fractional Differences
Regarding the possibility of fractional differences during conversion, the answer is still no for integers. This is because the step width between double values represented as mantissa * 2^exponent is always a power of two. Therefore, there is never a difference smaller than 2 between two double values, resolving any rounding issues.
The above is the detailed content of Can All Integer Values be Perfectly Represented as Doubles?. For more information, please follow other related articles on the PHP Chinese website!