我正在尝试使用数学库的一些函数,例如(pow,floor等)。但是,当我尝试将它们与像这样的Big Int一起使用时...
let x = Math.pow(100n, 100n);
我得到了
TypeError:无法将BigInt值转换为数字
当然我也可以自己实现,比如...
const BigMath ={
pow(num, pow){
let total;
for(let i = 0; i < pow; i++){
if(!total) total = num;
else total = total * num;
}
return total;
}
}
let x = BigMath.pow(100n, 100n);
但我不想回到过去,重新实现所有的函数。特别是因为从我的实现来看,它应该能够处理它,没有问题。
那么我如何使用BigInt来处理Math.*呢?
发布于 2020-11-22 18:54:38
对于pow()
,您可以简单地使用**
运算符:
Math.pow(2, 175)
// 4.789048565205903e+52
2**175
// 4.789048565205903e+52
2n**175n
// 47890485652059026823698344598447161988085597568237568n
与大多数Math
函数一样,floor()
与整数无关。
事实上,只有5个Math
函数与整数相关:
Math.abs()
Math.max()
Math.min()
Math.pow()
Math.sign()
其他函数涉及实数:
atan2
)cos
,acos
,sin
,asin
,tan
,atan
,atan2
)atan
,cosh
,acosh
,sinh
,D47,D48),hypot
)log2
)random
)imul
)、clz32
、fround
因此,下面是BigInt
的Math
的等价物
const bigMath = {
abs(x) {
return x < 0n ? -x : x
},
sign(x) {
if (x === 0n) return 0n
return x < 0n ? -1n : 1n
},
pow(base, exponent) {
return base ** exponent
},
min(value, ...values) {
for (const v of values)
if (v < value) value = v
return value
},
max(value, ...values) {
for (const v of values)
if (v > value) value = v
return value
},
}
发布于 2018-08-16 10:48:08
BigInts是一种不同的数据类型,它有自己的方式,不能进行比较,也不能在表达式中这样使用
typeof 123; // 'number'
typeof 123n; // 'bigint'
数字不能表示超出安全整数限制的数字,这就是为什么不允许在BigInts和BigInts之间混合操作(比较运算符===,<,>除外),因为任何隐式转换都可能丢失信息
所以你能做的就是添加一个隐式类型转换
Number( Math.pow( Number(100n) , Number(100n) ) ); // 1.0000000000000005e+200
发布于 2021-09-08 22:26:05
您可以使用Basenumber.js,它允许BigInt和BigDecimal操作:
电源
let x = Base('100');
let y = Base('100');
let z = x.pow(y);
console.log( z.toString() );
console.log( z.toExponential(1) );
<script src='https://cdn.jsdelivr.net/gh/AlexSp3/Basenumber.js@main/BaseNumber.min.js'></script>
分部
let x = Base('1e+10000');
let y = Base('999999999999999999999999999999999');
let z = x.divide(y);
console.log(z.toString());
console.log(z.toExponential(1));
<script src='https://cdn.jsdelivr.net/gh/AlexSp3/Basenumber.js@main/BaseNumber.min.js'></script>
https://stackoverflow.com/questions/51867270
复制相似问题