从浮点数到两倍,以及从双点数到浮点的精度损失? [英] Precision loss from float to double, and from double to float?

查看:98
本文介绍了从浮点数到两倍,以及从双点数到浮点的精度损失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

应该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:

  1. 将浮点数提升为双倍或长双倍时,或者双倍为 提升为长整数,其值保持不变.
  2. 当双打 降级为浮点型,长型double降级为double或浮点型,或者 表示的值比要求的精度和范围大 通过其语义类型(参见6.3.1.8)被显式转换为 语义类型,是否可以准确表示要转换的值 在新类型中,它保持不变.如果要转换的值在 可以表示但不能表示的值的范围 确切地,结果是最近的较高值或最近的较低值 可表示的值,以实现定义的方式选择.如果 所转换的值超出了可以 表示,行为是不确定的
  1. When a float is promoted to double or long double, or a double is promoted to long double, its value is unchanged.
  2. 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)

float类型的prvalue可以转换为double类型的prvalue. 该值不变.这种转换称为浮点 促销.

A prvalue of type float can be converted to a prvalue of type double. The value is unchanged. This conversion is called floating point promotion.

并且 4.8 部分又名转化双

浮点类型的prvalue可以转换为的prvalue 另一个浮点类型. 如果源值可以准确 表示为目标类型,则转换结果为 确切的表示.如果源值在两个相邻值之间 目标值,则转换结果是 这些值之一的实现定义选择.否则, 行为是不确定的.允许的转换为浮点数 促销不包含在浮点转换中

A prvalue of floating point type can be converted to a prvalue of another floating point type. If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation. If the source value is between two adjacent destination values, the result of the conversion is an implementation-defined choice of either of those values. Otherwise, the behavior is undefined. The conversions allowed as floating point promotions are excluded from the set of floating point conversions

所以这些值应该完全相等.

So the values should be equal exactly.

这篇关于从浮点数到两倍,以及从双点数到浮点的精度损失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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