This probably isn't the answer you're looking for, and it may seem facetious, but in my own work, I pretty much imagine that I have this macro available to me. It has the handy advantage of working equally well on float
, double
, and long double
operands:
#define fp_is_exact(f) 0
But I confess I very rarely actually write things like
if(fp_is_exact(x))
do something the easy way;
else
do something the hard way;
I'm going to have to write the code to do it the hard way, anyway, and the "easy" code gets used so rarely that I might as well get out of the habit of imagining that it might ever be useful for anything.
In all seriousness: assume that floating-point numbers are never exact. Exactness is not what they're for. Just about anything you might ever need to represent as a floating-point variable is not an exactly-known quantity anyway, especially if it's something you measured in the real world like a distance or weight or velocity or something. (My favorite example: How far is it from Los Angeles to New York? In inches?)
Addendum: Climbing down off of my high horse, I have to admit, sometimes it's appropriate to assume that floating-point numbers are exact. Comparisons like if(f == 0)
or if(f == 1)
or if(f == 3)
are perfectly fine in practice. I'd have no hesitation comparing a floating-point variable for exact equality to an integer less than 10 -- or less than 100, if it came to that, and maybe also 0.5. But for just about any other number I might have in mind, or that I might be manipulating in a floating-point variable in a C program, the chance that it's exactly representable as a float
or double
is just about vanishingly small.