基于对数的解决方案计算大整数中不正确的位数
Logarithm-based solution calculates incorrect number of digits in large integers
我还没有足够的声誉点数来发表评论,但看到很多人(错误地)建议使用 log10 来计算正整数的位数。这对大数字来说是错误的!
long n = 99999999999999999L;
// correct answer: 17
int numberOfDigits = String.valueOf(n).length();
// incorrect answer: 18
int wrongNumberOfDigits = (int) (Math.log10(n) + 1);
// also incorrect:
double wrongNumberOfDigits2 = Math.floor(Math.log10(n) + 1);
基于对数的解决方案将错误地输出 18 而不是 17。
我想知道为什么。
Way to get number of digits in an int?
Fastest way to get number of digits on a number?
问题是在这种情况下 99999999999999999
不能精确表示为(双精度)floating-point 值。当作为 double
参数传递给 log10
.
时,最接近的值为 1.0E+17
log10(n)
值也是如此:16.999999999999999995657...
- 可以表示的最接近的值是 17
.
在数学上绝对正确。
任何非空整数(正数!)的位数是 log10(n)+1。毫无疑问!
正如 Brett Hale 所指出的那样,表示会出现问题。
所以,如果你想要,没问题,没有限制,计算非常准确:) 使用BigDecimal。
但最简单:使用 lengthof String:
Long l=99999999999999999L;
int len=l.toString().length();
如果您真的想要计算,请参阅
即:Logarithm of a BigDecimal
即:BigDecimal to the power of BigDecimal on Java/Android
我还没有足够的声誉点数来发表评论,但看到很多人(错误地)建议使用 log10 来计算正整数的位数。这对大数字来说是错误的!
long n = 99999999999999999L;
// correct answer: 17
int numberOfDigits = String.valueOf(n).length();
// incorrect answer: 18
int wrongNumberOfDigits = (int) (Math.log10(n) + 1);
// also incorrect:
double wrongNumberOfDigits2 = Math.floor(Math.log10(n) + 1);
基于对数的解决方案将错误地输出 18 而不是 17。
我想知道为什么。
Way to get number of digits in an int?
Fastest way to get number of digits on a number?
问题是在这种情况下 99999999999999999
不能精确表示为(双精度)floating-point 值。当作为 double
参数传递给 log10
.
1.0E+17
log10(n)
值也是如此:16.999999999999999995657...
- 可以表示的最接近的值是 17
.
在数学上绝对正确。
任何非空整数(正数!)的位数是 log10(n)+1。毫无疑问!
正如 Brett Hale 所指出的那样,表示会出现问题。
所以,如果你想要,没问题,没有限制,计算非常准确:) 使用BigDecimal。
但最简单:使用 lengthof String:
Long l=99999999999999999L;
int len=l.toString().length();
如果您真的想要计算,请参阅
即:Logarithm of a BigDecimal
即:BigDecimal to the power of BigDecimal on Java/Android