3 ms·
Wouldn't max( x,-x ) cover everything ?
by athrowaway3z 5y ago
Wouldn't max( x,-x ) cover everything ?
- Kranar 5y agoThat will not handle -0.0 unfortunately since 0 == -0.
- alisonkisk 5y agoThat doesn't matter because Math.max() knows the difference between +0.0 and -0.0. Try it and you'll see.
- bordercases 5y agoIt does that because of the way they implement arithmetic, not about an inherent property of the mathematical function `max`. The problem has to be solved once.
- alisonkisk 5y agoThe article's (dubious, as mentioned at the end) goal is finding the most efficient way in CPU time.
- kmm 5y agoNaively, max(a, b) would be implemented as return a >= b ? a : b; But if x is -0.0, you're back to the same problem that -0.0 >= +0.0 actually turns out to be true and not false, hence the return value will be -0.0. Looking at the actual implementation[0], doubleToRawLongBits is used again here to take care of this edge case. So it would work, but a lot slower than the version given in the article. 0: https://github.com/openjdk/jdk/blob/36e2ddad4d2ef3ce27475af6244d0246a8315c0c/src/java.base/share/classes/java/lang/Math.java#L1681 https://github.com/openjdk/jdk/blob/36e2ddad4d2ef3ce27475af6...
- andi999 5y agoCouldn't you also implement max as return a>b? a:b; (changing greater equal to just greater). Would the problem then still persist?
- kmm 5y agoPositive and negative zero cannot be distinguished by normal equality checks, meaning +0.0 == -0.0. Therefore, for consistency's sake +0.0 > -0.0 ought to be false, which would yield a return value of -0.0 for max(+0.0, -(+0.0))
- gvx 5y agoThat wouldn't solve it: max(0.0, -0.0) would be false ? 0.0 : -0.0 The problem is that 0.0 == -0.0. As long as you don't take care of signed zero, you cannot guarantee that abs(x) has no negative sign.