Java Reference
In-Depth Information
Example:
Math.sqrt(4)
Purpose:
To invoke a static method (a method that does not operate on an object) and supply
its parameters
S ELF C HECK
11. Why can't you call x.pow(y) to compute x y ?
12. Is the call System.out.println(4) a static method call?
154
155
C OMMON E RROR 4.3: Roundoff Errors
Roundoff errors are a fact of life when calculating with floating-point numbers.
You probably have encountered this phenomenon yourself with manual
calculations. If you calculate 1/3 to two decimal places, you get 0.33. Multiplying
again by 3, you obtain 0.99, not 1.00.
In the processor hardware, numbers are represented in the binary number system,
not in decimal. You still get roundoff errors when binary digits are lost. They just
may crop up at different places than you might expect. Here is an example:
double f = 4.35;
int n = (int) (100 * f);
System.out.println(n); // Prints 434!
Of course, one hundred times 4.35 is 435, but the program prints 434.
Computers represent numbers in the binary system (see Advanced Topic 4.2 ). In
the binary system, there is no exact representation for 4.35, just as there is no exact
representation for 1/3 in the decimal system. The representation used by the
computer is just a little less than 4.35, so 100 times that value is just a little less
than 435. When a floating-point value is converted to an integer, the entire
fractional part is discarded, even if it is almost 1. As a result, the integer 434 is
Search WWH ::




Custom Search