I've a problem with large numbers I think.
The calculation in Java:
int n = 4451 + 554 * 57;
n = n << 13 ^ n;
System.out.println(n * (n * n * 15731 + 789221) + 1376312589);
=> 587046333
In JavaScript:
var n = 4451 + 554 * 57;
n = n << 13 ^ n;
console.log(n * (n * n * 15731 + 789221) + 1376312589);
=> 4.043454188561781e+29
What is the problem in the JavaScript version and how can I fix it, so that the outcome of JavaScript is identical to the Java outcome?
EDIT: tried with: https://github.com/jtobey/javascript-bignum, but outcome is 0
var test = new BigInteger(295120061).multiply( new BigInteger(295120061)
.multiply(new BigInteger(295120061))
.multiply(new BigInteger(15731))
.add(new BigInteger(789221)))
.add(new BigInteger(1376312589));
=> test = 0
JavaScript does not have integer arithmetic, and all numbers are stored as 64-bit floats (double in Java). When JavaScript sees a bit-handling operator like << or ^, it temporarily converts the operands to 32-bit integers to perform the arithmetic, but then converts them back to 64-bit float. Thus, the last multiplication is performed as a floating-point operation in JavaScript. In Java, it is still an integer operation. This code performs the same operation in Java (I have now tested it, and the result is the same):
int n = 4451 + 554 * 57;
n = n << 13 ^ n;
double x = n;
System.out.println(x * (x * x * 15731 + 789221) + 1376312589);
If you want JavaScript code that works the same as Java, you will need a way to perform multiplication and addition that works the same way as Java does when you overflow. That is, it must treat the results of all operations as if they were in the range -231 and 231-1. There really isn't a reliable way to do this in JavaScript using its native arithmetic; even if you give it two values that have only 31 significant bits, when you multiply them you will get 62 significant bits, while JavaScript's "number" type only has 52 bits, which means some bits will get lost. There may be a JavaScript library that would allow you to do this kind of exact integer arithmetic, but I'm not an expert on JavaScript frameworks so I don't know what that would be. Maybe someone else will chime in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With