问题描述
我没有足够的声誉积分可以发表评论,但是无数次有人(错误地)建议使用log10来计算正整数的位数.这对于大数目是错误的!
I don't have enough reputation points yet to leave comments, but saw numerous times when people (incorrectly) suggest using log10 to calculate the number of digits in a positive integer. This is wrong for large numbers!
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.
The logarithm-based solutions will incorrectly output 18 instead of 17.
我想了解原因.
Way to get number of digits in an int?
Fastest way to get number of digits on a number?
推荐答案
问题在于,在这种情况下,99999999999999999
无法精确表示为(双精度)浮点值.当作为double
参数传递给log10
时,最接近的值为1.0E+17
.
The problem is that 99999999999999999
cannot be exactly represented as a (double precision) floating-point value in this case. The nearest value is 1.0E+17
when passed as a double
parameter to log10
.
log10(n)
值也是如此:16.999999999999999995657...
-可以表示的最接近值是17
.
The same would be true of the log10(n)
value: 16.999999999999999995657...
- the nearest value that can be represented is 17
.
这篇关于基于对数的解决方案计算大整数的位数不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!