Pregunta

When having a Double d, I'd like to know which Double' is the smalles possible value bigger than d.

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

> 0d + Double.MIN_VALUE
4.9E-324

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

> 1d + Double.MIN_VALUE
1.0

It has to do wit significant numbers I guess, but in short : I'm looking for a method that gives me the next double

nextDouble(0)==4.9E-324
¿Fue útil?

Solución 3

That is easy. Positive double's are ordered at bit level just the way longs are. So converting it to a long and increasing it and then back to a 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);
}

The same works for negative values. If you want to get the closest double that is bigger, then decrease the long representation.

In response to the alternative Math.nextUp(), here is the source code for that method:

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));
    }
}

This is equivalent with my code, that does the extra checks for infinity.

Otros consejos

Take a look at these functions.

public static double nextAfter(double start, double direction)

Returns the floating-point number adjacent to the first argument in the direction of the second argument. If both arguments compare as equal the second argument is returned.

public static double nextUp(double d)

Returns the floating-point value adjacent to d in the direction of positive infinity. This method is semantically equivalent to nextAfter(d, Double.POSITIVE_INFINITY); however, a nextUp implementation may run faster than its equivalent nextAfter call.

Do it this way:

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

From the JavaDoc:

An ulp of a double value is the positive distance between this floating-point value and the double value next larger in magnitude.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top