Why is NodeJS inaccurate with the addition of a large number?

I performed the same addition in PHP and NodeJS. PHP calculated correctly up to 1 billion iterations, but NodeJS correctly calculated only up to 100 million iterations.

This is the PHP code:

<?php
$start_time = time();
$j = 0;
for ($i = 0; $i <= 1000000000; $i++) {
    $j += $i;
}
$end_time = time();
echo "Time Taken: " . ($end_time - $start_time);
echo "\n";
echo "i: " . $i;
echo "\n";
echo "j: " . $j;
echo "\n";
?>

Which returned the following output:

Time Taken: 15
i: 1000000001
j: 500000000500000000

This is the NodeJS code:

var epoch = require('epoch.js');
var start_time = epoch().format('ss');
var i;
var j = 0;
for (i = 0; i <= 1000000000; i++) {
    j += i;
}
var end_time = epoch().format('ss');
var time_taken = end_time - start_time;
console.log("Time Taken: " + time_taken + " \ni: " + i + "\nj: " + j);

Which returned the following output:

Time Taken: 1 
i: 1000000001
j: 500000000067109000

Why is the variable jincorrect in NodeJS?

Edit:

As pointed out by @SalmanA (and confirmed by me), I would also like to ask why the maximum integer limit remains unchanged for Javascript on different processors, but changes for PHP?

+4
source share
2 answers

Since you changed the intention of the question, I felt that it was opening it again.

JavaScript , Number, 64- (IEEE 754-2008) ). , " " -9007199254740991 9007199254740991 . . :

> 9007199254740993
< 9007199254740992

Node.js , Number.MAX_SAFE_INTEGER, , .


PHP . :

    • PHP x64 8- * (-9223372036854775808... 9223372036854775807)
    • PHP x86 4- (-2147483648... 2147483647)
    • PHP, , 64- IEEE 754-2008, , JavaScript
  • PHP integer float

PHP x64 $j = int(500000000500000000), PHP_INT_MAX, float ( ) .

PHP x86 float, , PHP_INT_MAX, $j = float(5.0000000006710899E+17) **.


* Windows, ** precision

+3

javascript Number. MAX_SAFE_INTEGER is 9007199254740991

+2

Source: https://habr.com/ru/post/1692293/


All Articles