javascript 为什么 Math.min() > Math.max()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8848779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:46:21  来源:igfitidea点击:

Why Math.min() > Math.max()?

javascriptmathif-statementmaxmin

提问by auroranil

When I type in an array into the parameter of the javascript math minimum and maximum functions, it returns the correct value:

当我在 javascript 数学最小值和最大值函数的参数中键入一个数组时,它返回正确的值:

console.log( Math.min( 5 ) ); // 5
console.log( Math.max( 2 ) ); // 2

var array = [3, 6, 1, 5, 0, -2, 3];
var minArray = Math.min( array ); // -2
var maxArray = Math.max( array ); // 6

However, when I use the function with no parameters, it returns an incorrect answer:

但是,当我使用不带参数的函数时,它返回一个不正确的答案:

console.log( Math.min() ); // Infinity
console.log( Math.max() ); // -Infinity

This one returns false:

这个返回错误:

console.log( Math.min() < Math.max() );


Why does it do this?


它为什么这样做?

回答by KARASZI István

Of course it would, because the start number should be Infinityfor Math.min. All number that are lower than positive infinity should be the smallest from a list, if there are no smaller.

当然会,因为起始编号应该是Infinityfor Math.min。如果没有更小的数,所有小于正无穷大的数都应该是列表中的最小数。

And for Math.maxit's the same; all numbers that are larger than negative infinity should be the biggest if there are no bigger.

因为Math.max它是一样的;如果没有更大的数字,则所有大于负无穷大的数字都应该是最大的。

So for your first example:

所以对于你的第一个例子:

Math.min(5)where 5is smaller than positive infinity (Infinity) it will return 5.

Math.min(5)其中5小于正无穷大 ( Infinity) 它将返回5

Update

更新

Calling Math.min()and Math.maxwith an array parameter may not work on every platform. You should do the following instead:

使用数组参数调用Math.min()Math.max可能不适用于每个平台。您应该改为执行以下操作:

Math.min.apply(null, [ 1, 2, 3, 4 , 5 ]);

Where the first parameter is the scope argument. Because Math.min()and Math.max()are "static" functions, we should set the scope argument to null.

其中第一个参数是范围参数。因为Math.min()andMath.max()是“静态”函数,我们应该将 scope 参数设置为 null。

回答by AakashM

It's tricky, but important, to decide correctly what aggregate functionsshould do when passed the empty set.

当传递空集时,正确决定聚合函数应该做什么是很棘手但很重要的。

Sometimes it's 'intuitively obvious': What is the SUM of no elements? Zero, I'm sure everyone would readily say.

有时它“直觉上很明显”:没有元素的总和是多少?零,我相信每个人都会很容易地说。

Sometimes it's less so: What is the PRODUCT of no elements? Those with some mathematical training will quickly say "one", but this is not at all obvious.

有时情况并非如此:没有元素的 PRODUCT 是什么?受过一些数学训练的人很快就会说“一”,但这一点都不明显。

Then you get to MIN and MAX and wow! How did we get those infinities?

然后你会得到 MIN 和 MAX,哇!我们是如何得到这些无穷大的?



One way to decide what an aggregate function should do here is consider what behaviours we want to remain consistent, even with empty sets. For example, suppose we have these non-empty sets:

决定聚合函数在这里应该做什么的一种方法是考虑我们希望保持一致的行为,即使是空集。例如,假设我们有这些非空集:

A = { 1, 2, 3 } 
B = { 4, 5 }

Now, it's true here, and indeed for any non-empty sets, that

现在,这里是真的,实际上对于任何非空集合,

SUM(A union B) = SUM(SUM(A), SUM(B))
15 = 6 + 9

PRODUCT(A union B) = PRODUCT(PRODUCT(A), PRODUCT(B))
120 = 6 * 20

MIN(A union B) = MIN(MIN(A), MIN(B))
1 = MIN(1, 4)

Wouldn't it be nice, say the mathematicians, if these properties remain true even when one or both of the sets are empty? It surely would.

数学家们说,如果这些属性即使在一个或两个集合为空时仍然为真,那不是很好吗?肯定会的。

And it's maintainint thisbehaviour that decides what value we assign to SOME_AGGREGATE_FUNCTION(empty-set):

正是这种行为决定了我们分配给什么值SOME_AGGREGATE_FUNCTION(empty-set)

In order for

为了

SUM(A union B) = SUM(SUM(A), SUM(B))

to remain true when Ais empty and Bis not, we must have SUM(empty-set) = 0

要在A为空时保持真实B,我们必须有SUM(empty-set) = 0

In order for

为了

PRODUCT(A union B) = PRODUCT(PRODUCT(A), PRODUCT(B))

to remain true when Ais empty and Bis not, we must have PRODUCT(empty-set) = 1

要在A为空时保持真实B,我们必须有PRODUCT(empty-set) = 1

And finally:

最后:

In order for

为了

MIN(A union B) = MIN(MIN(A), MIN(B))

to remain true when Ais empty and Bis not, we need MIN(empty-set)to be a value which is guaranteed to be greater than any possible value in B, so that it doesn't 'interfere with' the result of MIN(B). And we get our answer: MIN(empty-set) = positive infinity

要在A为空且B不是为空时保持为真,我们需要MIN(empty-set)成为一个保证大于 B 中任何可能值的值,以便它不会“干扰” 的结果MIN(B)。我们得到了答案:MIN(empty-set) = positive infinity

回答by Matt

Why does it do this?

它为什么这样做?

Because thats what the standard saysshould happen;

因为这就是标准所说的应该发生的事情;

15.8.2.11 max ( [ value1 [ , value2 [ , … ] ] ] )

Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.

  • If no arguments are given, the result is ?-Infinity
  • If any value is NaN, the result is NaN.
  • The comparison of values to determine the largest value is done as in 11.8.5 except that +0 is considered to be larger than ?0.

15.8.2.11 最大值([value1[,value2[,…]]])

给定零个或多个参数,对每个参数调用 ToNumber 并返回结果值中的最大值。

  • 如果没有给出参数,结果是 ?-Infinity
  • 如果任何值为 NaN,则结果为 NaN。
  • 确定最大值的值的比较在 11.8.5 中完成,除了 +0 被认为大于 ?0。

15.8.2.12 min ( [ value1 [ , value2 [ , … ] ] ] )

Given zero or more arguments, calls ToNumber on each of the arguments and returns the smallest of the resulting values.

  • If no arguments are given, the result is Infinity.
  • If any value is NaN, the result is NaN.
  • The comparison of values to determine the smallest value is done as in 11.8.5 except that +0 is considered to be larger than ?0

15.8.2.12 分钟([ 值1 [ , 值2 [ , … ] ] ] )

给定零个或多个参数,对每个参数调用 ToNumber 并返回结果值中的最小值。

  • 如果未给出参数,则结果为 Infinity。
  • 如果任何值为 NaN,则结果为 NaN。
  • 确定最小值的值的比较在 11.8.5 中完成,除了 +0 被认为大于 ?0

p.s; It is non standard that Math.max()or Math.min()accepts an array. Use Math.max(a,b,c,d,e,...)etc instead.

ps; Math.max()Math.min()接受数组是非标准的。使用Math.max(a,b,c,d,e,...)等代替。

In Chrome at least;

至少在 Chrome 中;

Math.max([1,2,3,4]); // NaN

回答by Juho ?stman

It's the same reason why the sum of an empty list is usually defined as 0 and their product as 1: it is the identity element of the operation. That is, whenever you include -Infinity as an element when computing max, it does not affect the result; respectively for Infinity and min.

这与空列表的和通常定义为 0 而它们的乘积定义为 1 的原因相同:它是操作的标识元素。也就是说,只要在计算 max 时将 -Infinity 作为元素包含在内,都不会影响结果;分别为无穷大和最小值。

This is sensible because it allows desirable "associative" properties for the aggregate operations. For example, the sum of a list is the same as computing the sums of any sublists (maybe including empty) and summing them. Likewise for products, mins, maxes and so on.

这是明智的,因为它允许聚合操作所需的“关联”属性。例如,列表的总和与计算任何子列表(可能包括空)的总和并将它们相加相同。同样对于产品、分钟、最大值等。

回答by Lightness Races in Orbit

[ECMA-262: 15.8.2.11]:max ( [ value1 [ , value2 [ , ... ] ] ] )

Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.

  • If no arguments are given, the result is ?∞.
  • If any value is NaN, the result is NaN.
  • The comparison of values to determine the largest value is done as in 11.8.5 except that +0 is considered to be larger than -0.

The lengthproperty of the maxmethod is 2.

[ECMA-262: 15.8.2.11]:max ( [ value1 [ , value2 [ , ... ] ] ] )

给定零个或多个参数,对每个参数调用 ToNumber 并返回结果值中的最大值。

  • 如果没有给出参数,结果是?∞。
  • 如果任何值为NaN,则结果为NaN
  • 确定最大值的值的比较在 11.8.5 中完成,除了 +0 被认为大于 -0。

该方法的length属性max为 2。

[ECMA-262: 15.8.2.12]:min ( [ value1 [ , value2 [ , ... ] ] ] )

Given zero or more arguments, calls ToNumber on each of the arguments and returns the smallest of the resulting values.

  • If no arguments are given, the result is +∞.
  • If any value is NaN, the result is NaN.
  • The comparison of values to determine the smallest value is done as in 11.8.5 except that +0 is considered to be larger than -0.

The lengthproperty of the minmethod is 2.

[ECMA-262: 15.8.2.12]:min ( [ value1 [ , value2 [ , ... ] ] ] )

给定零个或多个参数,对每个参数调用 ToNumber 并返回结果值中的最小值。

  • 如果没有给出参数,则结果为 +∞。
  • 如果任何值为NaN,则结果为NaN
  • 确定最小值的值的比较在 11.8.5 中完成,除了 +0 被认为大于 -0。

该方法的length属性min为 2。

With no arguments, Math.minis a value you can use to calculate an iterative minimum, not a physical minimum value for the type. It does this by being the opposite: a physical maximum value for the type. (Similarly in the other direction for Math.max; and clearly +∞ < -∞is false.)

没有参数,Math.min是一个可用于计算迭代最小值的值,而不是该类型的物理最小值。它通过相反的方式做到这一点:类型的物理最大值。(对于Math.max;的另一个方向类似,显然+∞ < -∞false.

i.e.

IE

var a = [1,2,3,4,5];
var x = Math.min();
for (var i = 0; i < a.length; i++) {
    if (a[i] < x) { // will succeed on first iteration
                    // because `x` is initialised to highest possible value
       x = a[i];
    }
}

(In fact, it maysimply be that the standard is making implementation of Math.mineasier, since it probably initialises its result to +Infinity before doing its work on any argument present, using an algorithm similar to the above.)

(事实上​​,这可能只是标准使实现Math.min更容易,因为它可能在对存在的任何参数进行工作之前将其结果初始化为 +Infinity,使用类似于上述的算法。)

Of course, this example is slightly contrived since we could just write:

当然,这个例子有点做作,因为我们可以这样写:

 var x = Math.min(a[0], a[1], a[2], a[3], a[4]);

However, the loop is useful if we don't know the number of elements in the array, since the variant of Math.minyou're using that accepts an array is non-standard.

但是,如果我们不知道数组中的元素数量,则循环很有用,因为Math.min您使用的接受数组的变体是非标准的。

Even then, you can do:

即便如此,您也可以这样做:

 var x = Math.min.apply(null, a);
 //               ^ reflective function-call
 //                     ^ no object instance; function is "static"
 //                           ^ array of arguments

回答by Richard

Probably because the implementation initialises an internal comparison variable to the highest (for Math.min) or lowest (for Math.max), before starting to compare against the empty arrays, and then returns the value of this internal comparison variable which of course has not been changed.

可能是因为在开始与空数组进行比较之前,实现将内部比较变量初始化为最高(对于 Math.min)或最低(对于 Math.max),然后返回这个内部比较变量的值,这当然有没有被改变。

回答by Divya

I don't know for sure. But, just making a guess.

我不确定。但是,只是猜测。

Remember how we find the min. Declare a variable with an extremely high value (Infinity) and then go through the values and whenever you find a value which is less than the one stored in your variable, you store it instead as the new min.

记住我们如何找到最小值。声明一个具有极高值 (Infinity) 的变量,然后遍历这些值,只要发现一个值小于存储在变量中的值,就将其存储为新的最小值。

So, since you are not giving it any values to find the min for, it gives you the initial value i.e. Infinity.

因此,由于您没有为其提供任何值来查找最小值,因此它为您提供了初始值,即 Infinity。

Same for max.

最大相同。

回答by Shamim Hafiz

The idea is, mathematically without any parameter you actually have an undefined value for the minimum.

这个想法是,从数学上讲,没有任何参数,您实际上有一个未定义的最小值值。

As for implementation wise, usually the min value is initialized with a very large value(Infinity), which is then updated as smaller values are found. If no value is found, then you have Infinityas the min value.

至于实现方面,通常最小值被初始化为一个非常大的值(Infinity),然后在找到较小的值时更新该值。如果未找到任何值,则您将Infinity获得最小值。

The case is opposite with finding the maximum value and that is why you have -Infinity.

这种情况与找到最大值相反,这就是为什么你有-Infinity.

回答by visitor

When given no arguments, Math.min()equals infinity and Math.max()is -infinity.

当没有给定参数时,Math.min()等于无穷大并且Math.max()-infinity

This is probably to ensure that any value is smaller than the minimum found so far, and larger than the maximum so far.

这可能是为了确保任何值都小于迄今为止发现的最小值,并且大于迄今为止的最大值。

回答by AVee

Theoretically the outcome of those functions is can't be given. The Ecma specificationdictates the outcome of the Min and Max functions without arguments (See page 163).

理论上,这些函数的结果是无法给出的。Ecma规范规定了不带参数的 Min 和 Max 函数的结果(参见第 163 页)。

Obviously you can have all sort of arguments about what the outcome should be, but there isn't a strictly correct answer anyway. I guess Ecma choose this because it's the easiest to implement. Normally a max function works roughly like this

显然,您可以对结果应该是什么有各种争论,但无论如何都没有严格正确的答案。我猜 Ecma 选择这个是因为它最容易实现。通常最大函数的工作原理大致如下

result = -infinity;
foreach(arg in arguments)
    if(arg > result)
        result = arg;

As you can see, returning -infinity when the function is called without arguments requires no changes at all.

如您所见,在不带参数的情况下调用函数时返回 -infinity 根本不需要更改。