Java Reference
In-Depth Information
Table 2.3
Bit layout of the floating point primitives.
Type
Sign
Exponent
Significand
1 bit
float
8 bits
23 bits
1 bit
double
11 bits
52 bits
Round-off - Arithmetic operations often result in the need to round off between the
exact value and the value that can be represented by the floating-point type. A round-off
(or truncation) algorithm must be chosen by the designer of the language. Round-offs can
have significant impact on calculated values, especially during intermediate operations
where errors can build up.
Overflows/underflows - Similarly, a calculation may result in a number that is smaller
or larger than the floating-point type can represent. Again, the language designer must
select a strategy for how to handle such situations.
Decimal-binary conversion - The computer represents numbers in base 2. This can
result in loss of precision since many finite decimal fractions (0.1 for example) cannot
be represented exactly by binary fractions. (All finite binary fractions, however, can be
converted to finite decimal fractions.)
These complications can mean even simple calculations with floating-point
give surprising results. For example, the following code:
double d = 0.0;
for (int i = 1; i <= 10; i++) {
d+= 0.1;
}
does not result in d = 1.0 since 0.1 is not exact in binary format. For this
reason, it is best to avoid equality tests between floating-point values, as in
if (a == b) statement;
Instead you should normally test floating values with < , <= , >= , and > .However,
it may be sensible to test for equality to 0.0 if a divide by zero could occur.
2.11.2 Java floating-point
The bit allocations for the floating-point representations of the float and dou-
ble types in Java are shown in Table 2.3. For each type there is one bit for the
sign. The exponents contain 8 and 11 bits and the fractions contain 23 and 52
bits, respectively.
The exponent values 0 and 255 for float are reserved for the special cases
discussed below. Otherwise, a bias of 127 is subtracted, giving an effective expo-
nent range of
127. Similarly, for double the exponent values 0 and
2047 are reserved and subtracting a bias of 1023 gives an effective exponent
range of
126 to
+
1022 to
+
1023.
Search WWH ::




Custom Search