Java Reference
In-Depth Information
that you can represent in Java is 0111 1111 1111 1111 1111 1111 1111 1111
binary = 2,147,483,647 decimal. (The first bit is the sign bit. It is off for positive
values.)
To convert an integer into its binary representation, you can use the static
toString method of the Integer class. The call Integer.toString(n,
2) returns a string with the binary digits of the integer n . Conversely, you can
convert a string containing binary digits into an integer with the call
Integer.parseInt(digitString, 2) . In both of these method calls, the
second parameter denotes the base of the number system. It can be any number
between 0 and 36. You can use these two methods to convert between decimal and
binary integers. However, the Java library has no convenient method to do the
same for floatingpoint numbers.
Now you can see why we had to fight with a roundoff error when computing 100
times 4.35. If you actually carry out the long multiplication, you get:
138
139
1 1 0 0 1 0 0 * 1 0 0.0 1 | 0 1 1 0 | 0 1 1 0 | 0 1 1 0
...
1 0 0.0 1 | 0 1 1 0 | 0 1 1 0|0 1 1 0 ...
1 0 0.0 1 | 0 1 1 0 | 0 1 1 0 | 0 1 1 ...
0
0
1 0 0.0 1 | 0 1 1 0 | 0 1 1 0 ...
0
0
_____________________________________
1 1 0 1 1 0 0 1 0.1 1 1 1 1 1 1 1 ...
That is, the result is 434, followed by an infinite number of 1s. The fractional part
of the product is the binary equivalent of an infinite decimal fraction 0.999999 ș,
which is equal to 1. But the CPU can store only a finite number of 1s, and it
discards some of them when converting the result to a decimal number.
R ANDOM F ACT 4.1: The Pentium Floating-Point Bug
In 1994, Intel Corporation released what was then its most powerful processor, the
first of the Pentium series. Unlike previous generations of Intel's processors, the
Pentium had a very fast floating-point unit. Intel's goal was to compete
Search WWH ::




Custom Search