[Slightly OT]: More on ints and floats

Tim Peters tim.one at comcast.net
Mon Apr 7 21:45:24 EDT 2003


[Steve Holden]
> ...
> As a matter of pure mathematics the integers are a subset of the reals,
> which are a subset of the complex numbers.
>
> Unfortunately pure mathematics and floating-point arithmetic only tend to
> intersect in the brains of people like Tim Peters.

The relationship can be formalized easily enough, but it's not so useful to
do so unless you work in that field:  computer floats are a peculiarly lumpy
and finite subset of the rational numbers, but the computer-float basic
operations (+ - * /) "usually" deliver different results than the same-named
operations on rationals.  The float operations can be defined precisely, but
the definitions are difficult to work with and reason about.  Knuth wasn't
the only one to note that many a good mathematician has given up in
frustration after trying to rigorously analyze just a few lines of
floating-point code.

For that reason I don't think there's much value in conflating computer ints
and computer floats:  the identities the latter fail to satisfy are
endlessly surprising to people.  Like addition and multiplication aren't
associative for floats, cancellation laws are shot all to hell for floats
(x+y == x+z doesn't imply y==z for floats), and so on.  This makes reasoning
hard.

OTOH, 754 float arithmetic has an inexact flag, set whenever the result of a
basic float operation differs from what the rational operation on the same
inputs would deliver.  Computer languages (including Python) overwhelmingly
failed to give users sane ways to get at this flag (among others).  If you
could get at it, it would be a lot easier to use floats for speed and
automatically detect when results became approximations.

Note that the IBM proposal for decimal arithmetic:

    http://www2.hursley.ibm.com/decimal/

doesn't distinguish between floats and integers.  It's an interesting mix
where the number of significant digits isn't unbounded, but where the
maximum is user-specified.  Make that big enough, and you can safely use the
same arithmetic for floating and integer calculations.  Figuring out how big
"big enough" is in advance can be tricky, though.  Setting the max # of
digits to 999999999 is a good trick -- provided you don't care how long
division takes <wink>.






More information about the Python-list mailing list