Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reduce wrongly returning infinity

when I try to use math power in reduce it’s not working as expected and returns infinity

const array1 = [1,2,3,4];

const initialValue = 0;
const sumWithInitial = array1.reduce(
  (a,b) => a + Math.pow(b, b + a),
  0
);

console.log(sumWithInitial);

but if there’s only 1-3 numbers in arr1 it works as intended

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As of the last iteration, you’re exceeding the capacity of the JavaScript number type (which is an IEEE-754 double-precision binary floating point value). It has nothing to do with reduce, it’s just that Math.pow(4, 4 + 531450) (the last value produced by your reduce loop) goes past the limit:

console.log(Math.pow(4, 4 + 531450));

You can see when pow will do that via the Number::exponentiate abstract operation in the specification (in the text, infinity is denoted by +∞𝔽, negative infinity by -∞𝔽). This is just a fact of trying to use a 64-bit value to try to represent a truly, truly, truly massive number.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading