Re: double is integer?
- From: Joseph M. Newcomer <newcomer@xxxxxxxxxxxx>
- Date: Sat, 03 Feb 2007 20:12:57 -0500
This is problematic at best. While it might work, in general it is not a safe thing to do
because what if your value is 2.0000000000001 or 1.99999999999999? After doing a lot of
floating point computations, you may have a value close to but not precisely an integer.
For example
double d = 10.0;
double q = d / 3.0;
double t = q * 3.0;
you might assume that d == t, which will not be true, and isInteger(d) may be true but
isInteger(t) will not be.
On the whole, this is a very risky thing to consider doing. You should never assume that
any computation involving a double will ever produce an integer value. For that matter,
if the integer value is very large, the double might lose low-order precision anyway.
There is no reliable way to actually compare doubles to integers and know that the double
is an integer value. Typically, you might consider
if( (d - ceil(d)) < fuzzfactor)
but that is about as good as it gets.
joe
On Sat, 3 Feb 2007 16:44:06 +0100, "Guido Franzke" <guidof73@xxxxxxxx> wrote:
Hello NG,Joseph M. Newcomer [MVP]
the following source let's me check if double is integer:
bool isInteger(const double& d)
{
if ( d == (double)((int)d) ) return true;
return false;
}
isInteger(2.); -> should return true
isInteger(2.5); -> should return false
isInteger(2.001); -> should return false
My question: Is this ok, or will I get problems? Is there another (secure)
possibility?
TIA
Guido
email: newcomer@xxxxxxxxxxxx
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm
.
- Follow-Ups:
- Re: double is integer?
- From: Doug Harrison [MVP]
- Re: double is integer?
- From: GT
- Re: double is integer?
- References:
- double is integer?
- From: Guido Franzke
- double is integer?
- Prev by Date: Re: Recommend a debugger
- Next by Date: Re: OnCommand
- Previous by thread: Re: double is integer?
- Next by thread: Re: double is integer?
- Index(es):