print 30 digits of a double value in c++

雨燕双飞 提交于 2019-12-11 06:42:45

问题


My understanding is that numeric_limits::max_digits10 gives the max number of digits after the decimal point that are available. But if I setprecision() to a value that is greater than this, it still gives me nonzero digits beyond this max value :

assert(std::numeric_limits<double>::max_digits10 == 17);
std::cout << std::setprecision(30) << double(.1) << '\n';

This prints out:

0.100000000000000005551115123126

Are the digits beyond 17 not to be trusted to be accurate?


回答1:


Converting the 53 bit (leading 1 implied) mantissa of the double to binary fixed point:

0.00011001100110011001100110011001100110011001100110011010

This equals the decimal value

0.1000000000000000055511151231257827021181583404541015625

which matches the question's result to 30 digits

0.100000000000000005551115123126

However what could be a 54th bit is unknown, and if you consider this as a range of possible values, the binary fixed point numbers just below and above would be

0.000110011001100110011001100110011001100110011001100110001
0.000110011001100110011001100110011001100110011001100110101

representing decimal values:

0.099999999999999984734433411404097569175064563751220703125
0.100000000000000012490009027033011079765856266021728515625

which implies 16 or 17 digits of precision. So the 30 digits of precision are only accurate if you consider the double precision number to be an exact representation rather than the closest representation.



来源:https://stackoverflow.com/questions/44739874/print-30-digits-of-a-double-value-in-c

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