Java Reference
In-Depth Information
public static final double E = 2.7182818284590452354 ;
public static final double PI = 3.14159265358979323846 ;
Of course, these constants are actually irrational numbers and cannot be precisely
expressed as a fraction, or by any finite decimal number. 1 This means that whenever
we try to represent them in a computer, there is always rounding error. Let's sup‐
pose we only want to deal with eight digits of π, and we want to represent the digits
as a whole number. We can use a representation like this:
314159265 · 10 −8
This starts to suggest the basis of how floating-point numbers work. We use some of
the bits to represent the significant digits ( 314159265 , in our example) of the num‐
ber and some bits to represent the exponent of the base ( -8 , in our example). The
collection of significant digits is called the signiicand and the exponent describes
whether we need to shift the significand up or down to get to the desired number.
Of course, in the examples we've met until now, we've been working in base-10.
Computers use binary, so we need to use this as the base in our floating-point exam‐
ples. This introduces some additional complications.
The number 0.1 cannot be expressed as a finite sequence of
binary digits. This means that virtually all calculations that
humans care about will lose precision when performed in
floating point, and rounding error is essentially inevitable.
Let's look at an example that shows the rounding problem:
double d = 0.3 ;
System . out . println ( d ); // Special-cased to avoid ugly representation
double d2 = 0.2 ;
// Should be -0.1 but prints -0.09999999999999998
System . out . println ( d2 - d );
The standard that describes floating-point arithmetic is IEEE-754 and Java's support
for floating point is based on that standard. The standard uses 24 binary digits for
standard precision and 53 binary digits for double precision.
As we mentioned briefly in Chapter 2 , Java can be more accurate than the standard
requires, by using hardware features if they are available. In extremely rare cases,
usually where very strict compatability with other (possibly older) platforms is
required, this behavior can be switched off by using strictfp to mandate perfect
compliance with the IEEE-754 standard. This is almost never necessary and the vast
majority of programmers will never need to use (or even see) this keyword.
1 In fact, they are actually two of the known examples of transcendental numbers .
Search WWH ::

Custom Search