Math exercise not computing correctly
Sundararajan Athijegannathan
sundararajan.athijegannathan at oracle.com
Fri Sep 2 11:04:23 UTC 2022
Hmm.. I think using Java's BigInteger from nashorn is an option.
java.math.BigInteger.valueOf(2 * 5 * 103).multiply(new java.math.BigInteger("3030214670981671")
-Sundar
________________________________
From: nashorn-dev <nashorn-dev-retn at openjdk.org> on behalf of Bruno Borges <bruno.borges at gmail.com>
Sent: 02 September 2022 04:20
To: nashorn-dev at openjdk.org <nashorn-dev at openjdk.org>
Subject: Math exercise not computing correctly
Hey all,
I am playing with factorization, and the following problem does not eval to the right value.
I tried the same with Node and it worked fine.
2 * 5 * 103 * 3030214670981671 = 3121121111111121130
-> https://www.wolframalpha.com/input?i=2+*+5+*+103+*+3030214670981671
Java computes the correct result: 3121121111111121130
Nashorn (v15.4) computes the following result: 3121121111111120896
Node.js (v16.14.2) computes the following result: 3121121111111121000
As you may know, this is because numbers in JavaScript are represented as double, and then we lose precision.
The solution for Node.js, is the use of BigInt(number), or appending the letter 'n' after each number:
> 2n * 5n * 103n * 3030214670981671n
3121121111111121130n
What would be the best workaround for Nashorn?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/nashorn-dev/attachments/20220902/793b5c12/attachment.htm>
More information about the nashorn-dev
mailing list