Python 3 behavior: Divide by zero with no exceptions

Topic closed. No more discussion for this topic.

Thanks for having time with this.

Wrong

x =0.001
sin(x)/x = 0.9999998333333416

python 3.10 on windows 10

even in lisp

(print (/ (sin 0.001) 0.001)) -> 0.9999999 
1 Like

Sorry, my bad.

When x approach 0, it’s nearly 1, but when x = 0, sinc(x) = 1

R does this, and it’s very very nice to use:

> 1/0
[1] Inf
> -1/0
[1] -Inf
> -1/0 + 7
[1] -Inf
> Inf - Inf
[1] NaN
> 0/0
[1] NaN
> Inf * 0
[1] NaN
etc.

Julia does the same:

julia> 1/0
Inf

julia> -1/0
-Inf

julia> -1/0 + 7
-Inf

julia> Inf - Inf
NaN

julia> 0/0
NaN

julia> 0^0
1

julia> Inf * 0
NaN

It’s no coincidence - these rules are laid out very precisely by IEEE 754.

The Wikipedia page for IEEE 754 links to quotes supporting the idea that this is not just for “esoteric numbers people” (my words), but for everybody:

It is a common misconception that the more esoteric features of the IEEE 754 standard discussed here, such as extended formats, NaN, infinities, subnormals etc., are only of interest to numerical analysts, or for advanced numerical applications. In fact the opposite is true: these features are designed to give safe robust defaults for numerically unsophisticated programmers, in addition to supporting sophisticated numerical libraries by experts. The key designer of IEEE 754, William Kahan notes that it is incorrect to “… [deem] features of IEEE Standard 754 for Binary Floating-Point Arithmetic that …[are] not appreciated to be features usable by none but numerical experts. The facts are quite the opposite. In 1977 those features were designed into the Intel 8087 to serve the widest possible market… Error-analysis tells us how to design floating-point arithmetic, like IEEE Standard 754, moderately tolerant of well-meaning ignorance among programmers”.[40]

I definitely understand that the backward-compatibility issues are real and large, but I do wish more languages would take IEEE 754 whole-cloth at face value, rather than re-litigating which parts they like or don’t like.

4 Likes

I think this misrepresents mathematics. Your statement is true if you limit calculations to the real number line, but this is not the only kind of mathematics there is. And there are lots of disadvantages to doing that. Other languages (e.g. R, Julia, Javascript - see my previous post) have shown that it can be much more robust to not limit yourself to the grade-school real number line.

IEEE 754 uses the real numbers extended by Inf, -Inf, and NaN, and therefore becomes algebraically complete (in the mathematical sense) without need for throwing exceptions (though exceptions can still be detected) when you “leak outside the system”, because you can’t leak outside the system. All operations are well-defined.

1 Like

Thanks for the reply, but the topic has already closed.

If you want to see how CPython can do this in coding, check here