[Python-ideas] Floating point contexts in Python core
Stephen J. Turnbull
stephen at xemacs.org
Fri Oct 12 05:40:56 CEST 2012
Oscar Benjamin writes:
> But the fpectl module IIUC wouldn't work for 1 / 0.
No, and it shouldn't.
> Since Python has managed to unify integer/float division now it
> would be a shame to introduce any new reasons to bring in
> superfluous .0s again:
With all due respect to the designers, unification of integer/float
division is a compromise, even a mathematical kludge. I'm not
complaining, it happens to work well for most applications, even for
me (at least where I need a computer to do the calculations :-).
Practicality beats purity.
> with context(zero_division='infinity'):
> x = 1 / 0.0 # float('inf')
> y = 1 / 0 # I'd like to see float('inf') here as well
I'd hate that. Zero simply isn't a unit in any ring of integers; if I
want to handle divide-by-zero specially (rather than consider it a
programming error in preceding code) a LBYL non-zero divisor test or a
try handler for divide-by-zero is appropriate.
And in the case of
z = -1 / 0.0
should it be float('inf') (complex) or -float('inf') (real)?
(Obviously it should be the latter, as most scientific programming is
done using real algorithms. But one could argue that just as integer
is corrupted to float in the interests of continuity in division
results, float should be corrupted to complex in the interest of a
larger domain for roots and trigonometric functions.)
> I've spent 4 hours this week in computer labs with students using
> Python 2.7 as an introduction to scientific programming. A significant
> portion of that time was spent explaining the int/float division
> problem. They all get the issue now but not all of them understand
> that it is specifically about division: many are putting .0s
> everywhere.
A perfectly rational approach for them, which may appeal to their
senses of beauty in mathematics -- I personally would always write
1.0/0.0, not 1/0.0, and more mathematically correct than what you try
to teach them. I really don't understand why you have a problem with
it. Your problem seems to be that Python shouldn't have integers,
except as an internal optimization for a subset of floating point
operations. Then "1" could always be an abbreviation for "1.0"!
> I expect it to be easier when we use Python 3 and I can simply
> explain that there are two types of division with two different
> operators.
Well, it's been more than 40 years since I studied this stuff in
America, but what they taught 10-year-olds then was that there are two
ways to view division: in integers with result and remainder, and as a
fraction. And they used the same operator! Not to mention that the
algorithm for reducing fractions depends on integer division. It's a
shame students forget so quickly. :-)
More information about the Python-ideas
mailing list