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
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?
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/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?
Share Improve this question asked Mar 26, 2012 at 6:04 monkey blotmonkey blot 9853 gold badges10 silver badges18 bronze badges4 Answers
Reset to default 8It'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.
Look at Number.MAX_VALUE
.
- The
MAX_VALUE
property has a value of approximately 1.79E+308.- Values larger than
MAX_VALUE
are represented as "Infinity".
Javascript numbers cannot be that big.
If you type
javascript:123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
in your address bar, you'll also get Infinity
.
You need to use a bignum library.
The number that you are starting with, 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890, is Infinity
, and Math.sqrt(Infinity)
is Infinity
.
What you need is a big integer library to simulate it, for example, http://www.leemon./crypto/BigInt.html; then with that you can take your big integer to the power of 0.5 to calculate the square root.