Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
14 changes: 14 additions & 0 deletions tests/math_max_min.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Loading