public static double NextAfter(double x, double y) {
long bits;
if (Double.IsNaN(x)) {
return x;
}
if (Double.IsNaN(y)) {
return y;
}
if (x == y) {
return y;
}
if (x == 0) {
bits = BitConverter.DoubleToInt64Bits(y) & 1L<<63;
return BitConverter.Int64BitsToDouble(bits | 1);
}
// At this point x!=y, and x!=0. x can be treated as a 64bit
// integer in sign/magnitude representation. To get the next
// representable neighbor we add or subtract one from this
// integer.
bits = BitConverter.DoubleToInt64Bits(x);
if (0 < x && x < y || 0 > x && x > y) {
bits++;
} else {
bits--;
}
return BitConverter.Int64BitsToDouble(bits);
}