[英]Floating point constants in templated code
I have a template function operating on a floating point argument.我有一个模板 function 对浮点参数进行操作。 The function is templated so that a caller can use either float
, double
or any other floating point data type. function 是模板化的,因此调用者可以使用float
、 double
或任何其他浮点数据类型。
At one point in my code, I compare a value with zero (or any other floating-point constant).在我的代码中,我将一个值与零(或任何其他浮点常量)进行比较。 Should I use 0.0
or 0.0f
for the comparison?我应该使用0.0
还是0.0f
进行比较?
template<T> void f(T a){
// should I use 0.0 or 0.0f in the following line?
if(a == 0.0){
}
}
While this is not causing any problems at the moment, I'd like to know what the usual practice is.虽然目前这不会造成任何问题,但我想知道通常的做法是什么。
I'd suggest我建议
if (a == T(0)) ...
I would suggest simply 0
.我建议简单地0
。 According to the promotion rules for numeric types, 0
will get promoted to the type of the floating-point operand a
.根据数值类型的提升规则, 0
将被提升为浮点操作数a
的类型。 Promotion of a constant is a compile-time transformation, it won't slow your program down at all.常量的提升是一种编译时转换,它根本不会减慢您的程序速度。
On the other hand, using 0.0
will force a run-time conversion of the other operand to double, which probably is a non-issue, as the operand is most likely passed in an FPU register anyway.另一方面,使用0.0
将强制将另一个操作数的运行时转换为双倍,这可能不是问题,因为操作数很可能无论如何都传递到 FPU 寄存器中。 0.0f
will not cause conversion of floating-point operands, but if the template was ever used with an integral type, you'd get run-time conversion to float
. 0.0f
不会导致浮点操作数的转换,但如果模板曾经与整数类型一起使用,您将在运行时转换为float
。
You should not compare for equality on floating point number with a simple您不应该用简单的浮点数比较相等
if (value == 0.0) // or 0.0f, doesn't matter
because most of the time it won't yield the result you are expecting.因为大多数时候它不会产生您期望的结果。 You should check if value
is enough close to the number you are expecting.您应该检查value
是否足够接近您期望的数字。 That is:那是:
if (abs(value - 0.0) < epsilon)
where epsilon is something little enough for you application domain.其中 epsilon 对您的应用程序域来说足够小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.