Re: double is integer?



"Joseph M. Newcomer" <newcomer@xxxxxxxxxxxx> wrote in message
news:0dcas2lrmirbjg293b14fd9odq39ide0au@xxxxxxxxxx
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


How about:

bool isInteger(const double& d)
{

long int i = (long int) d;
if ((double) i == d)
{
// we have an integer
return true;
}
else
return false;
}


.



Relevant Pages

  • Re: C floating point
    ... > C supports single precision floating point and double precision ... > that fixed floating point is more accurate than single precision ... int dollar; ...
    (comp.lang.c)
  • Re: gcc strangeness
    ... binary floating point arithmetic, rather than gcc. ... The correct solution is to use rint(3), ... Switching to double precision will help but is still not a complete ...
    (freebsd-hackers)
  • Re: Problem in Float Arithmetic
    ... precision of an integer of the same number of bits of significance as the mantissa of the ... The problem, for example, is that 'float' has fewer bits than ... 'int', so it only becomes interesting when you start using 'double'. ... Floating point arithmetic on integer values that produces integer values is ...
    (microsoft.public.vc.mfc)
  • Re: how to use recursive algorithm to determine all of the arrangements?
    ... The simplest way is to check for integer overflow is to do the multiplication in floating point precision, and check if the result is larger than what would fit in whatever primitive type you're trying to store the value in. ... In the case of int, you could use long instead of double. ...
    (comp.lang.java.programmer)
  • [PATCH][PPC64] Handle altivec assist exception properly
    ... This is the PPC64 counterpart of the PPC32 Altivec assist exception ... Fortunately there are only a limited set of altivec instructions ... +static unsigned int eexp2 ... +/* Round to floating integer, ...
    (Linux-Kernel)