首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java中的log2 for BigInteger

Java中的log2 for BigInteger
EN

Stack Overflow用户
提问于 2017-03-16 06:18:04
回答 2查看 2K关注 0票数 1

想知道是否有一个API可以直接计算log_2?下面是我的当前代码,我将log_2(N)转换为log_e(N)/log_e(2)

顺便说一句,对于普通的Java双类型,没有直接计算log_2(double_value)的方法吗?

用编写的代码,

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-16 06:26:47

这是内置到BigInteger API中的。来自Javadoc:

公共int bitLength() 返回此BigInteger的最小两补表示中的位数,不包括符号位。对于正的BigInteger,这相当于普通二进制表示中的位数。(计算(ceil(log2(this < 0 ? -this : this+1))).)

票数 8
EN

Stack Overflow用户

发布于 2019-09-30 06:37:26

如果您想要部分位数:

代码语言:javascript
复制
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));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42826607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档