Javascript总结大整数 [英] Javascript summing large integers

查看:130
本文介绍了Javascript总结大整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中我想用以下方法创建一个大型布尔数组(54个元素)的二进制哈希:

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;
}

简而言之:它创建了一个最小的整数来存储一个布尔数组。现在我的问题是javascript显然使用浮动作为默认值。我必须创建的最大数量是2 ^ 54-1但是一旦javascript达到2 ^ 53,它就会开始做奇怪的事情:

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

有没有办法在javascript中使用整数而不是浮点数?或大整数求和?

Is there any way of using integers instead of floats in javascript? Or large integer summations?

推荐答案

Javascript在内部使用浮点数。

Javascript uses floating point internally.

什么是一个数字可以达到的JavaScript的最高整数值而不会丢失精度?

换句话说,你不能使用超过53位。在某些实现中,您可能被限制为31.

In other words you can't use more than 53 bits. In some implementations you may be limited to 31.

尝试将位存储在多个变量中,使用字符串或获取 bignum library ,或者如果你只需要处理整数,那么 biginteger library

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.

这篇关于Javascript总结大整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆