我正在尝试使用数学库的一些函数,例如(pow、floor 等)。然而,当我尝试将它们与这样的 Big Int 一起使用时......
let x = Math.pow(100n, 100n);
Run Code Online (Sandbox Code Playgroud)
我明白了
类型错误:无法将 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);
Run Code Online (Sandbox Code Playgroud)
但我不想返回并重新实现所有功能。特别是从我的实现看来,它应该能够毫无问题地处理它。
那么我如何使用 BigInt 处理 Math.* 呢?
Yuk*_*élé 10
pow()您可以简单地使用运算符**:
Math.pow(2, 175)
// 4.789048565205903e+52
2**175
// 4.789048565205903e+52
2n**175n
// 47890485652059026823698344598447161988085597568237568n
Run Code Online (Sandbox Code Playgroud)
floor()像大多数Math函数一样与整数无关。
事实上,只有 5 个Math函数与整数相关:
Math.abs()Math.max()Math.min()Math.pow()Math.sign()所有其他函数都涉及实数:
cos, acos, sin, asin, tan, atan, atan2)cosh, acosh, sinh, asinh, tanh, atanh)sqrt, cbrt, hypot)round,ceil,floor,trunc)exp, expm1, log, log10, log1p, log2)random)clz32,fround,imul)因此,这相当于Mathfor BigInt:
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
},
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3273 次 |
| 最近记录: |