Posts

Showing posts with the label floating-point

Why is Java's double/float Math.min() implemented this way?

20 4 I was looking through some things in the source of java.lang.Math , and I noticed that while Math.min(int, int) (or its long counterpart) is implemented this way: public static int min(int a, int b) { return a <= b ? a : b; } And this makes complete sense to me and it is the same as what I would do. However, the double/float implementation is this: public static float min(float a, float b) { if (a != a) { return a; } else if (a == 0.0F && b == 0.0F && (long)Float.floatToRawIntBits(b) == negativeZeroFloatBits) { return b; } else { return a <= b ? a : b; } } I'm completely dumbfounded. Comparing a to itself? What's the second check even for? Why isn't it implemented in the same way as the int/lo...

Does casting to or from a double and a float preserve infinity and NaN?

23 When casting double infinity to float and vice versa, will it still be infinity? Is it the same with NaN? c++ floating-point nan Share Improve this question Follow edited Apr 7 at 5:03 Peter Cordes 242k 34 34 gold badges 417 417 silver badges 593 593 bronze badges ...

Is the inverse of std::numeric_limits::infinity() zero?

Is there anything in the C++ standard (or the IEEE 754 floating-point standard) that guarantees that 1./std::numeric_limits<double>::infinity() is zero (or at least a small number)? Yes, according to the GNU C library reference manual (assuming IEEE 754): Infinities propagate through calculations as one would expect: for example, 2 + ∞ = ∞, 4/∞ = 0 https://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html You may want to check if your C++ compiler uses IEEE 754: How to check if C++ compiler uses IEEE 754 floating point standard Any finite number divided by infinity results in zero under IEEE 754 (and therefore the same in most typical C++ implementations). If the sign of the of numerator and denominator differ, the result will be negative zero, which is equal to zero. IEEE 754-2008 6.1 says: The behavior of infinity in floating-point arithmetic is derived from the limiting cases of real arithmetic with operands of arbitrarily large magnitude,...