Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

c++ - Setting and checking with a float constant

I know there are a lot of questions on here about why float equality comparison is usually a bad idea. I understand float representation issues, rounding issues, silent promotion of floats to doubles, the dangers in relying upon arithmetic at the bit level, etc. But it seems to me that this should be fine, and no questions I found seem to cover this:

static const float MARKER = -500.0f; // some value well outside the range of valid values
std::vector<float> some_floats = {MARKER, 0.5f, 100.0f, 9.5f, MARKER, 0.f};
for (size_t i = 0; i< some_floats.size(); ++i) {
    if (some_floats[i] == MARKER) {             
       std::cout << i << std::endl;
    } else {
       // do some math
    }
}

The output is as expected:

0
4

If I have -Wfloat-equal enabled (in gcc, but similar in other compilers), it will flag the comparison line as dangerous: comparing floating point with == or != is unsafe. And pretty much all the answers on here say not to use == or !=, period. But I don't see why it's a problem here. I'm only setting the constant once and re-using it everywhere else it's used, and there is never any manipulation of that constant (e.g. arithmetic). Am I missing something? What about 0.0f, even if not set as a constant?

question from:https://stackoverflow.com/questions/65939711/setting-and-checking-with-a-float-constant

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As long as you're confident MARKER and its copies won't be altered by arithmetic functions or something, there's no issue doing a simple comparison.
Maybe consider not using -Wfloat-equal globally but disable warnings locally:

    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wfloat-equal"
    /* your code */
    #pragma GCC diagnostic pop

Or a portable equivalent: https://www.fluentcpp.com/2019/08/30/how-to-disable-a-warning-in-cpp/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...