3 ms·
So the correct implementation of fits_long would be this? int fits_long(double value) { double max = (double) (1L << 52) double min = (
by qznc 7y ago
So the correct implementation of fits_long would be this?
int fits_long(double value)
{
double max = (double) (1L << 52)
double min = (double) -max;
return min <= value && value <= max;
}
(assuming a 64bit long)
- aidenn0 7y agoIt depends on the semantics of fits_long. There are values outside of your min/max range that are representable by 64-bit integers, but if you convert them to a double and back, you may get a different value (off by as much as 4096, since, IIRC, the specification allows any rounding strategy).
- mulle_nat 7y agoThat would allow a double with a fractional part to return true though, which is not the intention. If you do this before the casted comparison, the cast shouldn't produce an undefined value. I think this is a good solution without using the math library and having access to the FP status registers. Otherwise the lrint solution seems better. int fits_long(double value) { double max = (double) (1L << 52) double min = (double) -max; if( min <= value && value <= max) return( (double) (long) value == value); return( 0); }