Code Complete
Code Complete

Reputation: 3206

Math.nextUp(arg) is always same as arg + Math.ulp(arg)?

Math.nextUp(arg) is always same as arg + Math.ulp(arg) or am I missing something?

System.out.println( 0.5 + Math.ulp(0.5));         // 0.5000000000000001 
System.out.println( Math.nextUp(0.5));            // EXACTLY same
System.out.println( Math.nextAfter(0.5, 1000));   // EXACTLY same

But -1, -2, -0.5 are the only exclusions (?) from the "rule" above that were found so far. Besides, the difference is always only in the rightmost decimal digit printed:

    System.out.println(Math.nextUp(-0.5));     // -0.49999999999999994
    System.out.println(-0.5 + Math.ulp(-0.5)); // -0.4999999999999999

    System.out.println(Math.nextUp(-1.0));     // -0.9999999999999999
    System.out.println(-1.0 + Math.ulp(-1.0)); // -0.9999999999999998

    System.out.println(Math.nextUp(-2.0));     // -1.9999999999999998
    System.out.println(-2.0 + Math.ulp(-2.0)); // -1.9999999999999996

public static double ulp(double d)

Returns the size of an ulp of the argument. An ulp, unit in the last place, of a double value is the positive distance between this floating-point value and the double value next larger in magnitude.

ulp of a specific real number value is the distance between the two floating-point values bracketing that numerical value.

public static double nextUp(double d)

Returns the floating-point value adjacent to d in the direction of positive infinity.

According to API, Math.nextUp(arg) and arg + Math.ulp(arg) should be equivalent for any arg (besides maybe some special values like NaN, Infinity, MAX_VALUE, MIN_VALUE)...

Upvotes: 2

Views: 108

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 223702

No. Consider -1. The ULP of -1 is 2−52. Numbers in the interval (−2, −1] are spaced 2−52 apart. However, numbers in the interval (−1, −½] are spaced 2−53 apart. So the next number up from −1 is −1+2−53, not −1+2−52.

Upvotes: 3

Related Questions