Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - When to use C float comparison functions?

In the latest C++ standard, I noticed the following macros :

bool isgreater(float x, float y);
bool isgreaterequal(float x, float y);
bool isless(float x, float y);
bool islessequal(float x, float y);
bool islessgreater(float x, float y);
bool isunordered(float x, float y);

These macros are from C (7.12.14 and 7.12.14).

So, why would someone use these macros, instead of operators? Is there anything special that these macros are doing (like checking for inf), or are they the same as their corresponding operator?

C++ example :

#include <iostream>
#include <cmath>

int main()
{
  float x=0.2;
  float y=0.5;
  std::cout << x << " < " << y << " : " << std::boolalpha << std::islessequal( x, y ) << std::endl;
  std::cout << x << " < " << y << " : " << std::boolalpha << ( x <= y ) << std::endl;
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Unlike the relational operators, these macros do really only return a boolean value and do never raise any floating point exception.

In short: You only have to deal with true/false and nothing else.


references:

The Open Group descriptions (not the C or C++ standard, but highly relevant in the Unix/Linux world and almost always similar to the standards):

C++ standard:

C Library [c.math]:

The classification/comparison functions behave the same as the C macros with the corresponding names defined in 7.12.3, Classification macros, and 7.12.14, Comparison macros in the C Standard. Each function is overloaded for the three floating-point types, as follows [...]

C standard:

7.12.14 Comparison macros

[...] For any ordered pair of numeric values exactly one of the relationships — less, greater, and equal — is true. Relational operators may raise the ‘‘invalid’’ floating-point exception when argument values are NaNs. For a NaN and a numeric value, or for two NaNs, just the unordered relationship is true. The following subclauses provide macros that are quiet (non floating-point exception raising) versions of the relational operators, and other comparison macros that facilitate writing efficient code that accounts for NaNs without suffering the ‘‘invalid’’ floating-point exception. In the synopses in this subclause, real-floating indicates that the argument shall be an expression of real floating type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...