Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript summing large integers

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?

like image 558
Raven Avatar asked Dec 29 '10 20:12

Raven


People also ask

How do you handle large numbers in JavaScript?

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.

How do you add two large numbers in Java?

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.

How do you sum numbers in JavaScript?

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.


2 Answers

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.

like image 117
martona Avatar answered Sep 19 '22 06:09

martona


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' 
like image 26
Mahmoud K. Avatar answered Sep 18 '22 06:09

Mahmoud K.