📜 ⬆️ ⬇️

Mathematical uncertainties on the example of 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.

Note:

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.

In general, there are quite a lot of uncertain situations in mathematics. For example, this is a division by 0.
Typing in console
')
1/0 

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

 0**0 

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

image

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

It is possible that someone is indignant right now and shouts that the answer is simple: IEEE 754. And if I am not mistaken with the help of it, we agreed that any number in the power of 0 is 1.

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

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

1. The release of errors in case of incorrect actions

Examples:

 1/0 # ZeroDivisionError log(0) #ValueError 

2. Returning incorrect values

Example:

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

3. Return special values:

+ -Inf, nan

Example:

 inf=float('inf') inf-inf #nan 

In my opinion this is confusing.

Literally today I noticed an interesting PHP behavior:

 var_dump(mt_rand(INF,INF)); //  INF  INF - NULL?? //        false. 

I am categorically against 2 options and probably support 1.

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

Source: https://habr.com/ru/post/454352/


All Articles