Mathematical Uncertainties in Python

    Hello! We often use familiar numbers in our favorite programming languages. Habitual is 1, -1.5, pi or even complex. But NaN, + Inf, -Inf is used by us much less often.


    In the article, I use the elementary functions of Python version 3.6.8, but much will be relevant for other languages, for example, for JS.

    There are quite a lot of uncertain situations in mathematics. For example, this is divided by 0.
    By typing in the console


    You will get a ZeroDivisionError error. Expected, you say? Yes. Let's try another example:


    As you know, 0 to the power of 0 is a classic mathematical uncertainty.
    However, Python says that this is 1. A reasonable question arises:


    Why are we not allowed to “shoot in the foot” divided by 0, but they report the wrong result with such an indefinite action?

    Perhaps someone is right now indignant and shouts that the answer is simple: IEEE 754. And if I am not mistaken it was with his help that we agreed that any number in degree 0 is 1.

    Here the most interesting begins. JavaScript also supports IEEE (0.1 + 0.2! = 0.3), but 1/0 in it is infinity, and not a division error by 0.

    As a result, we have (all examples for python):

    1. An error was thrown during incorrect actions


    1/0 # ZeroDivisionError
    log(0) #ValueError

    2. Returning incorrect values


    0**0  #1
    1**inf #1.0

    3. Returning special values:

    + -Inf, nan


    inf-inf #nan

    In my opinion this is confusing.

    Just today, I noticed an interesting PHP behavior:

    var_dump(mt_rand(INF,INF)); //случайное между INF и INF - NULL??
    //При этом функция должна возвращать только числа и false.

    I am categorically against the 2 options and probably support 1.

    Because, as the example with PHP shows, you need to use inf and nan with caution. What do you think?

    Also popular now: