JavaScript Integer math incorrect results

前端 未结 4 508
眼角桃花
眼角桃花 2020-12-09 07:17

I am just trying to implement a simple RNG in JS.

What\'s happening is javascript evaluates 119106029 * 1103515245 to be 131435318772912110

4条回答
  •  借酒劲吻你
    2020-12-09 07:31

    If done in C/C++ (double), the last numbers will be ...112 instead of 105 (which is correct). If performed with 'long double', the result will be as expected (...105). So it looks like the Javascript interpreter converts the numbers to 8-byte-double internally, does the calculation and does some unknown rounding which leads to a marginally better result than the C/C++ standard double calculation.

    GCC 4.5:

     int main(int argc, char** argv)
    {
     long double a = 119106029;
     long double b = 1103515245;
     long double c = a * b;
     printf("%.Lf\n", c);
    
     return 0;
    }
    

    Result:

    131435318772912105
    

    Expected:

    131435318772912105
    

    So I don't see a chance in Javascript without the aid of a BIGNUM library (if any).

    Regards

    rbo

提交回复
热议问题