diff --git a/src/lib.ts b/src/lib.ts index 61ad577..b381ea8 100644 --- a/src/lib.ts +++ b/src/lib.ts @@ -1844,10 +1844,12 @@ export static class Math { // -Infinity, not Number.MIN_VALUE: that is the smallest positive number, so the maximum of // negative numbers came out as it. With no arguments the result is -Infinity, and any NaN // makes it NaN. + // +0 is larger than -0 here, which `>` does not tell apart: Math.max(-0, 0) is 0 in either + // order (1 / -0 is -Infinity) let m = Number.NEGATIVE_INFINITY; for (const v of values) { if (isNaN(v)) return Number.NaN; - if (v > m) m = v; + if (v > m || (v == 0 && m == 0 && 1 / m < 0)) m = v; } return m; @@ -1859,10 +1861,12 @@ export static class Math { */ public min(...values: number[]): number { // +Infinity, not Number.MAX_VALUE, so that Math.min() and Math.min(Infinity) are Infinity + // -0 is smaller than +0 here, which `<` does not tell apart: Math.min(0, -0) is -0 in either + // order let m = Number.POSITIVE_INFINITY; for (const v of values) { if (isNaN(v)) return Number.NaN; - if (v < m) m = v; + if (v < m || (v == 0 && m == 0 && 1 / v < 0)) m = v; } return m; diff --git a/tests/math_max_min.ts b/tests/math_max_min.ts index 10680e6..20343d0 100644 --- a/tests/math_max_min.ts +++ b/tests/math_max_min.ts @@ -18,5 +18,19 @@ function main() { assert(Math.min(Number.POSITIVE_INFINITY) == Number.POSITIVE_INFINITY, "Math.min(Infinity)"); assert(isNaN(Math.min(Number.NaN, 1)), "Math.min(NaN, 1)"); + // +0 is larger than -0, which `>` and `<` do not tell apart: the answer depended on the order. + // Doubles made at run time (`-0` is the integer 0); 1 / -0 is -Infinity. + const scale = 1.5; + const negativeZero: number = -0.0 * scale; + const positiveZero: number = 0.0 * scale; + assert(1 / negativeZero < 0 && 1 / positiveZero > 0, "the zeros"); + assert(1 / Math.max(negativeZero, positiveZero) > 0, "Math.max(-0, 0) is 0"); + assert(1 / Math.max(positiveZero, negativeZero) > 0, "Math.max(0, -0) is 0"); + assert(1 / Math.max(negativeZero, negativeZero) < 0, "Math.max(-0, -0) is -0"); + assert(1 / Math.min(positiveZero, negativeZero) < 0, "Math.min(0, -0) is -0"); + assert(1 / Math.min(negativeZero, positiveZero) < 0, "Math.min(-0, 0) is -0"); + assert(1 / Math.min(positiveZero, positiveZero) > 0, "Math.min(0, 0) is 0"); + assert(Math.max(negativeZero, -1) == 0 && Math.min(positiveZero, 1) == 0, "zeros against others"); + print("ALL DONE"); }