在C ++中输出30位双精度值 [英] print 30 digits of a double value in c++

查看:162
本文介绍了在C ++中输出30位双精度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是numeric_limits :: max_digits10给出了小数点后可用的最大位数.但是,如果我将preprecision()设置为一个大于此值的值,它仍会为我提供超出此最大值的非零数字:

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';

打印输出:

0.100000000000000005551115123126

难道不相信17岁以上的数字是正确的吗?

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

推荐答案

将double的53位(隐含前导1)尾数转换为二进制不动点:

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

0.00011001100110011001100110011001100110011001100110011010

这等于十进制值

0.1000000000000000055511151231257827021181583404541015625

将问题的结果与30位数字匹配

which matches the question's result to 30 digits

0.100000000000000005551115123126

但是第54位是未知的,如果您认为这是一个可能的值范围,那么上下的二进制定点数将是

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

代表十进制值:

0.099999999999999984734433411404097569175064563751220703125
0.100000000000000012490009027033011079765856266021728515625

表示16或17位精度.因此,只有当您将双精度数字视为精确的表示形式而不是最接近的表示形式时,精度的30位数字才是准确的.

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.

这篇关于在C ++中输出30位双精度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆