本文介绍了从浮点数到两倍,以及从双点数到浮点的精度损失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
float fv = orginal_value; // original_value may be any float value
...
double dv = (double)fv;
...
fv = (float)dv;
应该fv确切等于original_value吗?精度可能会丢失吗?
SHOULD fv be equal to original_value exactly? Any precision may be lost?
推荐答案
是的,如果之间的dv
值没有变化.
Yes, if the value of dv
did not change in between.
在C99规范的转换6.3.1.5实际浮动类型部分中:
From section Conversion 6.3.1.5 Real Floating types in C99 specs:
- 将浮点数提升为双倍或长双倍时,或者双倍为 提升为长整数,其值保持不变.
- 当双打 降级为浮点型,长型double降级为double或浮点型,或者 表示的值比要求的精度和范围大 通过其语义类型(参见6.3.1.8)被显式转换为 语义类型,是否可以准确表示要转换的值 在新类型中,它保持不变.如果要转换的值在 可以表示但不能表示的值的范围 确切地,结果是最近的较高值或最近的较低值 可表示的值,以实现定义的方式选择.如果 所转换的值超出了可以 表示,行为是不确定的
- When a float is promoted to double or long double, or a double is promoted to long double, its value is unchanged.
- When a double is demoted to float, a long double is demoted to double or float, or a value being represented in greater precision and range than required by its semantic type (see 6.3.1.8) is explicitly converted to its semantic type, if the value being converted can be represented exactly in the new type, it is unchanged. If the value being converted is in the range of values that can be represented but cannot be represented exactly, the result is either the nearest higher or nearest lower representable value, chosen in an implementation-defined manner. If the value being converted is outside the range of values that can be represented, the behavior is undefined
对于C ++,请参见 4.6 部分(又称为 conv.fpprom )(使用的草稿:,我相信最终规格中也有类似的产品线
For C++, from section 4.6 aka conv.fpprom (draft used: n337 and I believe similar lines are available in final specs)
并且 4.8 部分又名转化双
所以这些值应该完全相等.
So the values should be equal exactly.
这篇关于从浮点数到两倍,以及从双点数到浮点的精度损失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!