首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Math.hypot

Math.hypot()函数返回它的所有参数的平方和的平方根,即:

Math.hypot(v1,v2,…,vn)=∑i=1nvi2=v12+v22+…+vn2\mathtt{\operatorname{Math.hypot}(v_1, v_2, \dots, v_n)} = \sqrt{\sum_{i=1}^n v_i^2} = \sqrt{v_1^2 + v_2^2 + \dots + v_n^2}

语法

代码语言:javascript
复制
Math.hypot([value1[, value2[, ...]]])

参数

value1, value2, ...任意多个数字

返回值

给定参数的平方和的平方根。如果至少有一个参数不能转换为数字,则返回NaN

描述

计算直角三角形的斜边或复数的幅度使用公式Math.sqrt(v1 * v1 + v2 * v2),其中v1和v2是三角形的边或实值和复值。要计算2维或更多维的距离,只需在平方根符号内添加更多的平方,如Math.sqrt(v1 * v1 + v2 * v2 + v3 * v3 + v4 * v4)。

这个函数使得更容易且更快地调用Math.hypot(v1,v2)或者Math.hypot(v1,v2,v3,v4,...)。

这也可以避免数量巨大的问题。在JS的双浮点数中可以表示的最大数字是Number.MAX_VALUE = 1.797 ... e + 308。如果你的数字大于1e154左右,取其平方将导致无穷大而导致拆除。例如,Math.sqrt(1e200 * 1e200 + 1e200 * 1e200)= Infinity。如果使用hypot()来代替,Math.hypot(1e200,1e200)= 1.4142 ... e + 200。非常小的数字也是如此。Math.sqrt(1e-200 * 1e-200 + 1e-200 * 1e-200)= 0,但Math.hypot(1e-200,1e-200)= 1.4142 ... e-200,这是一个很好的答案。

由于hypotMath?的静态方法,所以应该像这样使用:Math.hypot(),而不是作为你创建的?Math实例的属性(Math不是一个构造函数)。

如果不传入任何参数, 则返回 +0 .

如果参数列表中有至少一个参数不能被转换为数字,则返回NaN.

如果只传入一个参数, 则Math.hypot(x)的效果等同于Math.abs(x).

示例

使用Math.hypot()

代码语言:javascript
复制
Math.hypot(3, 4);        // 5
Math.hypot(3, 4, 5);     // 7.0710678118654755
Math.hypot();            // 0
Math.hypot(NaN);         // NaN
Math.hypot(3, 4, 'foo'); // NaN, +'foo' => NaN
Math.hypot(3, 4, '5');   // 7.0710678118654755, +'5' => 5
Math.hypot(-3);          // 3, the same as Math.abs(-3)

Polyfill

此函数可以使用如下代码模拟:

代码语言:javascript
复制
Math.hypot = Math.hypot || function() {
  var y = 0, i = arguments.length;
  while (i--) y += arguments[i] * arguments[i];
  return Math.sqrt(y);
};

避免下溢和溢出的polyfill:

代码语言:javascript
复制
Math.hypot = function (x, y) {
? // https://bugzilla.mozilla.org/show_bug.cgi?id=896264#c28
? var max = 0;
? var s = 0;
? for (var i = 0; i < arguments.length; i += 1) {
? ? var arg = Math.abs(Number(arguments[i]));
? ? if (arg > max) {
? ? ? s *= (max / arg) * (max / arg);
? ? ? max = arg;
? ? }
? ? s += arg === 0 && max === 0 ? 0 : (arg / max) * (arg / max);
? }
? return max === 1 / 0 ? 1 / 0 : max * Math.sqrt(s);
};

规范

Specification

Status

Comment

ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Math.hypot' in that specification.

Standard

Initial definition.

ECMAScript Latest Draft (ECMA-262)The definition of 'Math.hypot' in that specification.

Living Standard

?

浏览器兼容性

Feature

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Basic Support

38

(Yes)

27

No

25

7.1

Feature

Android

Chrome for Android

Edge mobile

Firefox for Android

IE mobile

Opera Android

iOS Safari

Basic Support

(Yes)

(Yes)

(Yes)

27

No

(Yes)

8

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com