Re: How to determine if double contains an integer value?
Martin Eisenberg wrote:
Alberto Ganesh Barbati wrote:
Greg Herlihy ha scritto:
DeCaf wrote:
I'm wondering if there is a "correct" way to check if a double
(or any other floating point type) contains an integer value?
I was thinking along the way of:
bool is_integer(double d)
{
return (d - (int)d) == 0.0;
}
I think a better way to determine whether a double represents
an exact integral value would be to compare the value modulo
1.0 against zero, like so:
if ( std::fmod( d, 1.0) == 0.0)
{
// integer value
}
I think using std::modf can be even better.
I'm asking both of you -- why?
A direct solution to a problem is always superior to an indirect
solution, that is, a solution produced as the byproduct of an otherwise
completely unnecessary and unrelated operation.
Assigning a floating point value to an int variable is not the purpose
of the routine we have been asked to write - testing whether a floating
point value is exactly divisible by 1.0 - on the other hand - is the
problem we need to solve. And as it happens there are (at least) two
standard functions that can provide the needed answer - either of which
will do so reliably.
The problem with the indirect solution it that it creates an unneeded
dependency: the correctness of the result is tied to the successful
outcome of the unnecessary operation. In this case, the return result
will be correct only when testing those floating points values that
have defined int value representations. But of course whether a
particular floating point value has a corresponding representation as
an int in C++ - is a question whose answer has no bearing whatsoever on
the question of whether that same floating point value is an exact
multiple of 1.0.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]