Home > Back-end >  what is the meaning of -Infinity (minus Infinity)
what is the meaning of -Infinity (minus Infinity)

Time:10-23

In this code:

function max(...numbers){
  let result = -Infinity; // <= here's the question
  for (let number of numbers) {
    if (number > result) result = number
  }
  return result;
}

I don't understand the meaning of the minus in front of infinity. The code returns the highest number given in the arguments. I returns Infinity without the minus.

CodePudding user response:

In this case, it's meant to be the lowest possible number, just like how Infinity is the highest possible number.

Since -Infinity is less than other non-infinity numbers, it can be used as the bottom of a max-number finding equation.

See these two examples of what happens with Infinity vs negative Infinity:

function max(...numbers){
  let result = -Infinity; // <= Negative
  for (let number of numbers) {
    if (number > result) result = number
  }
  return result;
}

console.log(max(5, 38, 71, 57))

function max(...numbers){
  let result = Infinity; // <= Positive (now the highest number)
  for (let number of numbers) {
    if (number > result) result = number
  }
  return result;
}

console.log(max(5, 38, 71, 57))

Do note that -Infinity and Infinity still have a sign, so if you multiply -Infinity and -5, it will result in Infinity.

CodePudding user response:

Infinity is the highest possible number. It also affects math like this:

let x = 1.797693134862315E 308; // highest possible number
console.log(x * 1.1);

let y = Infinity;

console.log(15   y);
console.log(y - 1000000);
console.log(y / 0);
console.log(0 / y);
console.log(1 / y);

-Infinity is the same, but negative.

  • Related