I am trying to use some functions of the Math library such as (pow, floor, etc). However, when I try to use them with a Big Int like this...
let x = Math.pow(100n, 100n);
I get
TypeError: Cannot convert a BigInt value to a number
of course I can implement this myself, something like...
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);
But I don't want to have to go back through and reimplement all of the functions. Especially since it seems like from my implementation it should be able to handle it no problem.
So how do I handle Math.* with a BigInt?
For pow()
you can simply use **
operator:
Math.pow(2, 175)
// 4.789048565205903e+52
2**175
// 4.789048565205903e+52
2n**175n
// 47890485652059026823698344598447161988085597568237568n
floor()
like most Math
functions is not relevant with integers.
In fact, only 5 Math
functions seam to be relevant with integers:
Math.abs()
Math.max()
Math.min()
Math.pow()
Math.sign()
All the other functions concern real numbers:
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
, f16round
, imul
, sumPrecise
)So, here is the equivalent of Math
for 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
},
}
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