36. Next floating-point value

Having an integer value such as 10 makes it very easy for us to obtain the next integer-point value, such as 10+1 (in the direction of positive infinity) or 10-1 (in the direction of negative infinity). Trying to achieve the same thing for float or double is not that easy as it is for integers.

Starting with JDK 6, the Math class has been enriched with the nextAfter() method. This method takes two arguments—the initial number (float or double) and the direction (Float/Double.NEGATIVE/POSITIVE_INFINITY)—and returns the next floating-point value. Here, it is a flavor of this method to return the next-floating point adjacent to 0.1 in the direction of negative infinity:

float f = 0.1f;

// 0.099999994
float nextf = Math.nextAfter(f, Float.NEGATIVE_INFINITY);

Starting with JDK 8, the Math class has been enriched with two methods that act as shortcuts for nextAfter() and are faster. These methods are nextDown() and nextUp():

float f = 0.1f;

float nextdownf = Math.nextDown(f); // 0.099999994
float nextupf = Math.nextUp(f); // 0.10000001

double d = 0.1d;

double nextdownd = Math.nextDown(d); // 0.09999999999999999
double nextupd = Math.nextUp(d); // 0.10000000000000002

Therefore, nextAfter() in the direction of negative infinity is available via Math.nextDown() and nextAfter(), while in the direction of positive infinity, this is available via Math.nextUp().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.108.119