Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Math.min() return positive infinity, while Math.max() returns negative infinity?

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

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?

like image 879
auroranil Avatar asked Jan 13 '12 10:01

auroranil


People also ask

Why does math Max return negative Infinity?

max is returning -Infinity when there is no argument passed. If no arguments are given, the result is -∞. So when you spread an empty array in a function call, it is like calling the function without an argument. But the result is negative infinity, not positive.

What is the difference between math MIN () and math MAX () functions?

when you execute Math. min(), you will get (Infinity) and when you execute Math. max(), you will get (-Infinity). by this result for sure if you compare Math.

Does math min work with negative numbers?

min() function is an inbuilt function in java that returns the minimum of two numbers. The arguments are taken in int, double, float and long. If a negative and a positive number is passed as an argument then the negative result is generated.

Why does Max return in math?

max() The Math. max() function returns the largest of the zero or more numbers given as input parameters, or NaN if any parameter isn't a number and can't be converted into one.


1 Answers

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

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

So for your first example:

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

Update

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

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.

like image 79
KARASZI István Avatar answered Oct 04 '22 04:10

KARASZI István