In JavaScript I would like to create the binary hash of a large boolean array (54 elements) with the following method:
function bhash(arr) { for (var i = 0, L = arr.length, sum = 0; i < L; sum += Math.pow(2,i)*arr[i++]); return sum; }
In short: it creates the smallest integer to store an array of booleans in. Now my problem is that javascript apparently uses floats as default. The maximum number I have to create is 2^54-1 but once javascript reaches 2^53 it starts doing weird things:
9007199254740992+1 = 9007199254740994
Is there any way of using integers instead of floats in javascript? Or large integer summations?
To represent integers larger than 2 to the 53rd power minus 1 in JavaScript, we can use the BigInt object to represent the values. It can be manipulated via normal operations like arithmetic operators — addition, subtraction, multiplication, division, remainder, and exponentiation.
math. BigInteger. add(BigInteger val) is used to calculate the Arithmetic sum of two BigIntegers. This method is used to find arithmetic addition of large numbers of range much greater than the range of biggest data type double of java without compromising with the precision of the result.
const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.
JavaScript uses floating point internally.
What is JavaScript's highest integer value that a number can go to without losing precision?
In other words you can't use more than 53 bits. In some implementations you may be limited to 31.
Try storing the bits in more than one variable, use a string, or get a bignum library, or if you only need to deal with integers, a biginteger library.
BigInt
is being added as a native feature of JavaScript.
typeof 123; // → 'number' typeof 123n; // → 'bigint'
Example:
const max = BigInt(Number.MAX_SAFE_INTEGER); const two = 2n; const result = max + two; console.log(result); // → '9007199254740993'
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