logoalt Hacker News

Aardwolfyesterday at 8:23 PM3 repliesview on HN

Python is extra annoying though with refusing to support division through zero the way other programming languages with IEEE floats do (i.e. output inf or nan instead of throwing an exception), even though it has no problem doing things like float('inf') / float('inf') --> nan. It specifically does it for division through zero as if it wants to be a junior grade calculator just for this one thing. They could at least have fixed this when breaking backwards incompatibility from python2 to 3...


Replies

dgrunwaldyesterday at 8:45 PM

In most languages, `x: float = 0` involves an implicit conversion from int to float. In Python, type annotations have no impact on runtime behavior, so even though the type checker accepts this code, `type(x)` will be `int` -- python acts as if `int` was a subtype of `float`.

It would be weird if the behavior of `1 / x` was different depending on whether `0` or `0.0` was passed to a `x: float` parameter -- if `int` is a subtype of `float`, then any operation allowed on `float` (e.g. division) should have the same behavior on both types.

This means Python had to choose at least one:

1. division violates the liskov substitution principle

2. division by zero involving only integer inputs returns NaN

3. division by zero involving only float inputs throws exception

4. It's a type error to pass an int where a float is expected.

They went with option 3, and I think I agree that this is the least harmful/surprising choice. Proper statically typed languages don't have to make this unfortunate tradeoff.

show 1 reply
caditinpiscinamyesterday at 9:28 PM

Nah. Python gets it right; all high level languages should operate this way. Division by zero is a bug 90% of the time. Errors should never pass silently. Special cases aren't special enough to break the rules.

IEEE floats should be a base on which more reasonable math semantics are built. Saying that Python should return NaN or inf instead of throwing an error is like saying that Python should return a random value from memory or segfault when reading an out-of-bounds list index.

show 1 reply
pletnesyesterday at 8:26 PM

Just use numpy if you want to do math. Seriously.