float FLOAT = 1.0f;
double DOUBLE = 2.0;
float a = FLOAT / DOUBLE;
double b = FLOAT / DOUBLE;
a
和b
的计算方式相同吗?
FLOAT
和 DOUBLE
在编译时如何转换?
似乎默认转换是上转换以防止丢失。
实际上我正在 GPU 上进行一些对精度敏感的计算,代码应如下所示:
float a = FLOAT / 2.0 + 1.0/3.0;
其中代码包含非常长的表达式,其中包含许多数字和变量(实际上是从 Matlab 代码生成的)。
那么我该如何控制这种转换行为呢?
除了将所有数字写成 2.0f
(表达式中的数千个数字)。
最佳答案
根据C标准(6.3.1.8常用算术转换)
Otherwise, if the corresponding real type of either operand is double, the other operand is converted, without change of type domain, to a type whose corresponding real type is double.
因此在声明的两个初始化表达式中
float a = FLOAT / DOUBLE;
double b = FLOAT / DOUBLE;
float
类型的操作数转换为 double
类型。因此,表达式的结果具有 double 类型。在第一个声明中,结果进一步转换为 float
,因为变量 a
的类型为 float
。
关于c - C如何处理混合精度运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49362740/