Java中Math.max(float,float)方法里var0 != var0的作用是什么?
Math.max(float var0, float var1)里var0 != var0判断的作用 Great question! Let's break down exactly what that quirky-looking check is doing:
核心原因:检测NaN(非数值)
That var0 != var0 condition is a standard way to check if var0 is a NaN (Not-a-Number). In Java's floating-point rules, NaN is the only value where x != x evaluates to true—every other float (positive/negative infinity, positive/negative zero, regular numbers) will always equal itself.
Why this matters for Math.max
The Java language specification dictates that any comparison involving NaN should return false. So if we didn't have this check, and var0 was NaN, the final var0 >= var1 ? var0 : var1 logic would always return var1—since NaN >= anyValue is false. But that's not the behavior we want from Math.max: if either input is NaN, the method should return NaN to follow floating-point standards.
结合代码里的其他逻辑
Let's quickly cover the rest of the method to put this in context:
- The second condition handles positive vs negative zero: when both inputs are 0.0F, but one is negative zero (detected via
Float.floatToRawIntBitswhich checks the underlying bit pattern), it returns the positive zero (var1), since positive zero is considered "greater" than negative zero. - The final else clause is the straightforward case: return the larger of the two regular floats.
Example to see it in action
// Returns NaN, which is correct per floating-point rules System.out.println(Math.max(Float.NaN, 10.5F)); // Without the NaN check, this would incorrectly return 10.5F
内容的提问来源于stack exchange,提问作者Kamil Bęben

