Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't Math.nextAfter(Double.MAX_VALUE, 1) equal to Double.INFINITY?

According to the Javadoc:

public static double nextAfter(double start,
                           double direction)

...

  • If start is equal to ± Double.MAX_VALUE and direction has a value such that the result should have a larger magnitude, an infinity with same sign as start is returned.

But according to this example:

System.out.println(Double.MAX_VALUE);
System.out.println(Math.nextAfter(Double.MAX_VALUE, 1));
System.out.println(Math.nextAfter(Double.MAX_VALUE, 1) == Double.POSITIVE_INFINITY);

Output:

1.7976931348623157E308
1.7976931348623155E308
false

Eh? Not only is it not Double.POSITIVE_INFINITY, it's actually smaller in magnitude.

...157E308
...155E308

Am I just completely misreading the Javadoc?

like image 613
Andy Turner Avatar asked Jun 29 '17 13:06

Andy Turner


1 Answers

The docs are misleading.

The direction parameter needs to be greater than Double.MAX_VALUE for the returned value to have a larger result.

Since 1 is smaller, the output is the floating point number just before the one you provide.

The C++ docs (under IEEE754) are clearer and even spell out this edge case explicitly: http://en.cppreference.com/w/cpp/numeric/math/nextafter

like image 154
Bathsheba Avatar answered Nov 11 '22 12:11

Bathsheba