Search code examples
javascriptmathlargenumber

Maths in javaScript


I am making an algorithm that works with large numbers (up to 2^900), but a lot of operations are still not so large. And in this cases I would like to make normal maths instead of algorithms for large numbers. I have such part of code:

    if (a * b < 1e17)
    {
        return(a * b);
    }
    else
    {
        //some large numbers maths
        return(res);
    }

And I am not sure whether it is a good way to check if the result fits in a Number variable. I know that some languages not always return something big, when they are out of stack. How does javascript do it? Will if (a * b < 1e17) always give false, when a*b is too big?

You asked to clarify the problem. Well, if it is not clear, I make exact question: will this part of code work correctly for each possible numbers a and b (if real result of multiplication is less then 1e17 it has to enter if statement and if not - enter else)? Will it always "go to" else if a and b are both more than 9 digits length?

    if (a * b < 1e17)
    {
        return(a * b);
    }
    else
    {
        //some large numbers maths
        return(res);
    }

Solution

  • Yes this code will work correctly. The Number data type in JavaScript does not suffer from a "wrap around" problem like the numeric data types in some other programming languages, where a calculation may overflow and produce a result that's completely wrong.

    The Number datatype does have limited precision because it's stored in a fixed amount of memory. The Number data type is precise to only around 16 significant digits. For example, multiplying two numbers with 10 significant digits does not give you a number with 20 correct significant digits: only the first 16 or 17 will be correct.