← 中文资源

简体中文版本

Math.hypot 避开中间溢出

Math.hypot 内部避免平方和的中间溢出:分量大到 1e200 时手写 sqrt(x*x+y*y) 得到 Infinity,hypot 仍给出精确长度,多维也一次到位。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

naive sqrt: Infinity
hypot: 1.414213562373095e+200
3-4-5: 5
3d: 3
with zeros: 7
single negative: 9
with Infinity: Infinity
NaN alone: NaN

实现说明

各个操作都建立在顶层绑定之上:big。

使用要点

  • 演示输出是带标签的(naive sqrt:、hypot:、3-4-5:),每个操作都会留下自己的一行标注。

常见问题

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。 跨调用保留的状态放在这些顶层绑定里:big。

核心语句

const big = 1e200;

代码示例

// Square-summing by hand overflows for large components
const big = 1e200;
console.log('naive sqrt:', Math.sqrt(big * big + big * big));
console.log('hypot:', Math.hypot(big, big));

// Ordinary cases match the Pythagorean identity
console.log('3-4-5:', Math.hypot(3, 4));

// Any number of dimensions in one call
console.log('3d:', Math.hypot(1, 2, 2));

// Zeros do not disturb the result
console.log('with zeros:', Math.hypot(0, 0, 7, 0));

// hypot of a lone value is its absolute value
console.log('single negative:', Math.hypot(-9));

// Edge semantics: an Infinity anywhere wins, NaN poisons otherwise
console.log('with Infinity:', Math.hypot(Infinity, NaN));
console.log('NaN alone:', Math.hypot(NaN, 3));