检测从双倍转换为浮点时的精度损失 [英] Detecting precision loss when converting from double to float
问题描述
我写了一段代码,我必须从double转换为float值。我正在使用boost :: numeric_cast做这个转换,将提醒我任何溢出/下溢。不过,我也有兴趣知道,如果这种转换导致一些精度损失或不。
例如
double source = 1988.1012;
float dest = numeric_cast< float>(source);
生成具有值的目标值1988.1
有没有什么办法可以检测到这种精度损失/四舍五入
解决方案
你可以将浮点数转换回加倍和比较这个双原来的 - 这应该给你一个公平的指示,是否有一个精度损失。
I am writing a piece of code in which i have to convert from double to float values. I am using boost::numeric_cast to do this conversion which will alert me of any overflow/underflow. However i am also interested in knowing if that conversion resulted in some precision loss or not.
For example
double source = 1988.1012;
float dest = numeric_cast<float>(source);
Produces dest which has value 1988.1
Is there any way available in which i can detect this kind of precision loss/rounding
You could cast the float back to a double and compare this double to the original - that should give you a fair indication as to whether there was a loss of precision.
这篇关于检测从双倍转换为浮点时的精度损失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!