TYPES, VALUES, AND VARIABLES
Floating Point Operations
4.2.4
Java requires that floating point arithmetic behave as if every floating point
operator rounded its floating point result to the result precision.
Inexact
results
must be rounded to the representable value nearest to the infinitely precise result;
if the two nearest representable values are equally near, the one with its least sig
nificant bit zero is chosen. This is the IEEE 754 standard's default rounding mode
known as
round to nearest
.
Java uses
round toward zero
when converting a floating value to an integer
( 5.1.3), which acts, in this case, as though the number were truncated, discarding
the mantissa bits. Rounding toward zero chooses at its result the format's value
closest to and no greater in magnitude than the infinitely precise result.
Java floating point operators produce no exceptions ( 11). An operation that
overflows produces a signed infinity, an operation that underflows produces a
signed zero, and an operation that has no mathematically definite result produces
NaN. All numeric operations with NaN as an operand produce NaN as a result. As
has already been described, NaN is unordered, so a numeric comparison operation
involving one or two NaNs returns
false
and any
!=
comparison involving NaN
returns
true
, including
x!=x
when
x
is NaN.
The example program:
class Test {
public static void main(String[] args) {
//
An example of overflow:
double d = 1e308;
System.out.print("overflow produces infinity: ");
System.out.println(d + "*10==" + d*10);
//
An example of gradual underflow:
d = 1e 305 * Math.PI;
System.out.print("gradual underflow: " + d + "\n
");
for (int i = 0; i < 4; i++)
System.out.print(" " + (d /= 100000));
System.out.println();
//
An example of NaN:
System.out.print("0.0/0.0 is Not a Number: ");
d = 0.0/0.0;
System.out.println(d);
//
An example of inexact results and rounding:
System.out.print("inexact results with float:");
for (int i = 0; i < 100; i++) {
float z = 1.0f / i;
if (z * i != 1.0f)
System.out.print(" " + i);
}
System.out.println();
35
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved