hypot-approx.js (1368B)
1 load(libdir + "math.js"); 2 3 for (var i = -20; i < 20; i++) { 4 assertEq(Math.hypot(+0, i), Math.abs(i)); 5 assertEq(Math.hypot(-0, i), Math.abs(i)); 6 } 7 8 // The implementation must avoid underlow. 9 // The implementation must avoid overflow, where possible. 10 // The implementation must minimise rounding errors. 11 12 assertNear(Math.hypot(1e-300, 1e-300), 1.414213562373095e-300); 13 assertNear(Math.hypot(1e-300, 1e-300, 1e-300), 1.732050807568877e-300); 14 15 assertNear(Math.hypot(1e-3, 1e-3, 1e-3), 0.0017320508075688772); 16 17 assertNear(Math.hypot(1e300, 1e300), 1.4142135623730952e+300); 18 assertNear(Math.hypot(1e100, 1e200, 1e300), 1e300); 19 20 assertNear(Math.hypot(1e3, 1e-3), 1000.0000000005); 21 assertNear(Math.hypot(1e-300, 1e300), 1e300); 22 assertNear(Math.hypot(1e3, 1e-3, 1e3, 1e-3), 1414.2135623738021555); 23 24 assertNear(Math.hypot(1e1, 1e2, 1e3), Math.sqrt(1e2 + 1e4 + 1e6)); 25 assertNear(Math.hypot(1e1, 1e2, 1e3, 1e4), Math.sqrt(1e2 + 1e4 + 1e6 + 1e8)); 26 27 for (var i = 1, j = 2; i < 2; i += 0.05, j += 0.05) 28 assertNear(Math.hypot(i, j), Math.sqrt(i * i + j * j)); 29 30 for (var i = 1, j = 2, k = 3; i < 2; i += 0.05, j += 0.05, k += 0.05) 31 assertNear(Math.hypot(i, j, k), Math.sqrt(i * i + j * j + k * k)); 32 33 for (var i = 1, j = 2, k = 3, l = 4; i < 2; i += 0.05, j += 0.05, k += 0.05, l += 0.5) 34 assertNear(Math.hypot(i, j, k, l), Math.sqrt(i * i + j * j + k * k + l * l));