Logarithm-based solution calculates incorrect number of digits in large integers

这一生的挚爱 提交于 2019-12-06 10:41:52

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.

The same would be true of the log10(n) value: 16.999999999999999995657... - the nearest value that can be represented is 17.

guillaume girod-vitouchkina

It is mathematically absolutely correct.

Number of digit of any integer not null (positive !) is log10(n)+1. No doubt !

Problems arise with representations, as pointed by Brett Hale.

So, if you want, no problem, no limit, very accurate calculation :) use BigDecimal.

But simplest: use lengthof String:

Long l=99999999999999999L;
int len=l.toString().length();

If you really want to do calculation, see

that: Logarithm of a BigDecimal

that: BigDecimal to the power of BigDecimal on Java/Android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!