想知道是否有一个API可以直接计算log_2?下面是我的当前代码,我将log_2(N)转换为log_e(N)/log_e(2)。
顺便说一句,对于普通的Java双类型,没有直接计算log_2(double_value)的方法吗?
用编写的代码,
BigInteger x = BigInteger.valueOf(16);
BigInteger y = BigInteger.valueOf((long)(Math.log(x.longValue()) / Math.log(2)));
System.out.println(y.doubleValue()); // return 4.0 as expected发布于 2017-03-16 06:26:47
这是内置到BigInteger API中的。来自Javadoc:
公共int bitLength() 返回此
BigInteger的最小两补表示中的位数,不包括符号位。对于正的BigInteger,这相当于普通二进制表示中的位数。(计算(ceil(log2(this < 0 ? -this : this+1))).)
发布于 2019-09-30 06:37:26
如果您想要部分位数:
const twoToThe50th = Math.pow(2, 50);
const log2BigInt = (x: bigint) => {
let log = 0;
while (x > twoToThe50th) {
// Shift by 6 bytes to right to stay on byte boundaries
x = x >> BigInt(48);
log += 48;
}
// x is now small enough to be a Number, which we
// can pass to JavaScript's built in log2 function
return log + Math.log2(Number(x));
}https://stackoverflow.com/questions/42826607
复制相似问题