Search code examples
javascriptmathinfinitysquare-root

Math.sqrt() returns infinity?


Math.sqrt(); seems to work fine with any number less than 310 characters long.

However, any number 310 chars or over will return infinity...

If you want to test it out yourself, here it is on jsfiddle http://jsfiddle.net/gqhk9/2

Anyway, I need to get the square root of numbers including some which are 310 chars and longer.

How can I do that in js?


Solution

  • It's not an issue with Math.sqrt - get rid of the Math.sqrt call and you'll still see infinity. Basically, Javascript can't cope with numbers that big - it runs out of the range of 64-bit floating point IEEE 754 values. You'll need to find some sort of library for handling arbitrary-sized integers.

    Note that even for numbers smaller than 10309, you're still going to be losing information after the first ~15 digits. If you care about all of those digits, again you should be looking at specialist maths libraries.

    A quick look around the web found BigInt.js referenced a few times, but I don't know how good it is.