How to find the next Double in Java or Groovy?

With Double d, I would like to know that Double 'is the smallest possible value greater than d.

When d == 0, I know the answer, which will be Double.MIN_VALUE:

> 0d + Double.MIN_VALUE
4.9E-324

But what about all ohter numbers like 1d for example?

> 1d + Double.MIN_VALUE
1.0

I need to make significant numbers, but, in short, I'm looking for a method that gives me the following double

nextDouble(0)==4.9E-324
+4
source share
3 answers

It is easy. Positive doubles are ordered at the bit level in the same way as long ones. Thus, converting it to long and incrementing it, and then back to double, does the trick:

public static double nextDouble(double d)
{
    if (d != d) return d;
    if (d == Double.MAX_VALUE) return Double.POSITIVE_INFINITY;
    if (d == Double.NEGATIVE_INFINITY) return d;
    if (d == Double.POSITIVE_INFINITY) return d;

    d += 0.0;
    int dir = d < 0.0 ? -1 : 1; 
    return Double.longBitsToDouble(Double.doubleToLongBits(d) + dir);
}

. , , .

Math.nextUp() :

public static double nextUp(double d) {
    if( isNaN(d) || d == Double.POSITIVE_INFINITY)
        return d;
    else {
        d += 0.0d;
        return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
                                       ((d >= 0.0d)?+1L:-1L));
    }
}

, .

+2

.

public static double nextAfter(double start, double direction)

, . .

public static double nextUp(double d)

, d . nextAfter(d, Double.POSITIVE_INFINITY); , nextUp , nextAfter call.

+10

:

Double d = Math.random();
Double next = d + Math.ulp(d);

JavaDoc:

The ulp value of the double value is the positive distance between this floating point value and the double value, which is larger.

+5
source

Source: https://habr.com/ru/post/1533927/


All Articles