integer division with float result

David B. Held dheld at codelogicconsulting.com
Tue Nov 20 01:31:33 PST 2007


Stas Sergeev wrote:
> renoX Wrote:
>> In a statically typed language, the issue is which float type do you use 
>> for (int / int)?
>> For accuracy, it ought to be one with biggest precision, but it's also 
>> the slowest, and can be non-portable (x86 has 80-bit float, other CPU do 
>> not)
> 
> I don't think this is really a problem.
> For example, doing an integer calculus, you can
> get an overflow, because the compiler does not
> promote ints to long-longs for you. So if you have
> a very large values, you have to explicitly notify
> the compiler by doing casts. OTOH, it does promote
> the shorts to ints for you, when needed.
> Same is here: the float can be used by default, and
> if you really need a hight precision, then you have
> to resort to an explicit casts, I think.

The main problem is that as much as we would like to idealize and 
abstract away details about the representations of our numbers, that is 
simply not practical, even on GFLOPS desktops.  We *do* have to know the 
sizes of our numbers and whether they are integral or floating-point 
types.  It matters a *lot* in almost every operation you perform.

 From a number theory perspective ints and floats are a world apart.  It 
is true that integers are not a field because they are not closed under 
/.  However, that does not mean we should pretend that Z == R and force 
float opDiv(int, int).  The reality is that int != Z, either.  No, int 
== Z_2^32, and that *does* have a closed /, which makes it as much a 
field as R, and deserving of its own int opDiv(int, int).  Of course, 
the / defined on Z_n is different from int opDiv(int, int), but let us 
not concern ourselves with that minor detail.

The fact of the matter is that computers are *not* Turing machines. 
They have finite tapes, and the squares of those tapes have finite 
sizes.  And the operation of these putative TMs are sensitive to the 
size of the tape and the squares composing the tape.  No competent 
programmer can ignore this reality.  We have overflow and underflow and 
modular arithmetic on integral types.  That is fundamental to ALUs and 
will remain so for the forseeable future.  Trying to hide these facts 
from the user by defining float opDiv(int, int) is not doing her any 
favors.  FP arithmetic is expensive, and using it should be explicit, 
not implicit.

It's easy enough to define your own float div(int, int) function that 
gives the desired behavior.  And if you are bothered that it doesn't 
look like normal /, I would call that a feature and a benefit.

Dave



More information about the Digitalmars-d mailing list