简体   繁体   English

使用Wfloat-equal选项将浮点数与1或0进行比较

[英]Comparing a floating point to one or zero with Wfloat-equal option

I'm somewhat familiar with the issues around performing floating point equality comparisons in code. 我对在代码中执行浮点相等比较的问题有些熟悉。

Currently the code base I'm compiling on (GCC, Clang) have the following option enabled: -Wfloat-equal 目前我正在编译的代码库(GCC,Clang)启用了以下选项: -Wfloat-equal

And in the code base there's the following example comparison: 在代码库中有以下示例比较:

template <typename FloatType>
void foo(FloatType v) {
  if (v == FloatType(1)) {
   ...
  }
  else if (v == FloatType(0)) {
   ....
  }
}

The foo function is invoked as follows: foo函数调用如下:

double d = 123.98;
float f = 123.98f;

foo(d);
foo(f);

Given the special case of 1 and 0 which each have exact representations in floating points (double, float) and where the code is clearly after an exact equality and not something that is close by some minor difference - 给出1和0的特殊情况,每个情况都有浮点(double,float)中的精确表示,并且代码显然是在完全相等之后,而不是某些微小差异接近的东西 -

Is there a way to rewrite the code such that it will not raise the associated Wfloat-equal diagnostic and will also be portable and support both float and double types? 有没有办法重写代码,以便它不会提高相关的Wfloat相同的诊断,也将是可移植的,并支持浮点型和双重类型?

How about using std::equal_to . 如何使用std::equal_to As far as GCC is concerned it will disable a whole bunch of checks when processing the system headers including the float-equal 就GCC而言,它将在处理包括float-equal的系统头时禁用一大堆检查

template <typename FloatType>
void foo(FloatType v) {
  if (std::equal_to<FloatType>()(v,FloatType(1))) {
   ...
  }
  else if (std::equal_to<FloatType>()(v,FloatType(0))) {
   ....
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM