[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: checking for Not a Number?
- From: Glenn Maynard <glenn@...>
- Date: Wed, 27 Dec 2006 17:44:33 -0500
On Wed, Dec 27, 2006 at 04:09:19PM -0500, Rici Lake wrote:
> Regardless, the use of floating point to store integers is not at all
> problematic, except possibly for the lack of an integer divide
> primitive. As long as a computation (and all intermediate computations)
> can be represented exactly in 53 bits, the result will be entirely
> predictable regardless of floating point mode.
... on PC hardware. Embedded- and semi-embedded (eg. gaming consoles)
hardware is not always endowed with hardware doubles.
(I'm sure the new generation of gaming consoles are, but I've been in PC-
land for a while.)
> It is also worth mentioning that integer arithmetic is subject to
> similar inconsistencies. In particular, it's not at all uncommon to see
> code like this:
>
> Foo *make_foo_vector(size_t n) {
> if (n * sizeof(Foo) > MAX_ALLOC)
> return NULL; /* Or issue an error */
> return malloc(n * sizeof(Foo));
> }
>
> This is, of course, incorrect and may result in the successful return
> of a vector of less than n Foo's, which may in turn lead to a
> buffer-overrun. On machines where size_t is <= 32 bits, the code could
> be corrected by doing the computation at line 2 in double-precision
> floating point, although I suppose the correct solution is to divide
> instead of multiplying.
Most typical problems with integers--such as the above--are much more
obvious and predictable (as you say, "of course") than the problems
with floats. They also tend to be deterministic, doing precisely the
same thing on all platforms (with the same variable size).
I've written code in fixed-point for this reason, where I wanted non-
integral numbers, wanted the predictability of integers, and didn't
need the variable precision gained by floating-point. I find it much
easier to tell precisely what will happen with integer code.
Floats add in rounding modes, temporary registers with a greater precision
than the variables (leading to different results depending on optimizations),
different results on different platforms, NAN/INF special cases,
By comparison, it takes a bit of thinking to think of integer operations
with nonportable results. Bit ops on signed integers comes to mind,
right-shifting in particular (even if you assume two's-complement, sign
extension isn't guaranteed).
--
Glenn Maynard