Skip to content

Commit b7a5b10

Browse files
committed
added investigation of int-float comparisons
1 parent 151e06d commit b7a5b10

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

  • text/main/basics/simpleDataTypesAndOperations/bool

text/main/basics/simpleDataTypesAndOperations/bool/bool.tex

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,24 @@
3434
While \pythonil{5 > 6}\pythonIdx{>} is not \pythonilIdx{True}, \pythonil{6 > 5}\pythonIdx{>} is.
3535
It is also possible to compare floating point numbers with integers and vice versa.
3636
\pythonil{5.5 == 5}\pythonIdx{==} is \pythonilIdx{False}, while \pythonil{5.0 == 5} is \pythonilIdx{True}.
37+
%
38+
\gitEvalPython{bool_comparisons_int_float}{}{simple_datatypes/bool_comparisons_int_float.py}%
39+
\listingBox{exec:bool_comparisons_int_float}{Comparing integer and floating point numbers.}{,style=python_console_style,literate={0}{0\-}1 {1}{1\-}1 {2}{2\-}1 {3}{3\-}1 {4}{4\-}1 {5}{5\-}1 {6}{6\-}1 {7}{7\-}1 {8}{8\-}1 {9}{9\-}1,breakatwhitespace=false,breaklines=true}%
40+
41+
When comparing an integer with a floating point number, one might expect that one is converted to another.
42+
This, interestingly, does not seem to be the case.
43+
In \cref{exec:bool_comparisons_int_float}, we can see that \python\ handles comparisons of integers and floating point numbers more subtle.
44+
The comparisons work for small integers and floats without issue.
45+
If the numbers get larger, we first run in the issue with limited precision of the \pythonilIdx{float} datatype.
46+
It cannot store more than 15 or 16 decimal digits~(depending on the weather), and thus~\pythonil{1e300} is not actually~$10^{300}$ as one might expect.
47+
Instead only the first 16 zeros are there, the remaining digits can be considered as undefined, as their value depends on whatever results from the internal binary representation.
48+
49+
We now try to compare~$10^{400}$ to~\pythonil{1e400}.
50+
Knowing the limits of \pythonilIdx{float}, we recall that writing~\pythonil{1e400} is essentially equivalent to writing~\pythonilIdx{inf}~(if that constant was imported from the \pythonil{math} module).
51+
The comparison yields~\pythonil{False}, as it should.
52+
To get there, however, neither is \pythonil{10 ** 400} converted to a \pythonil{float}, nor is \pythonil{1e400} converted to an~\pythonilIdx{int}.
53+
Both would net us an~\pythonilIdx{OverflowError}.
54+
Thus, we find that the \pythonilIdx{float} datatype does not \inQuotes{infect} comparisons and that \python\ is actually quite elegant here.
3755

3856
Comparisons can also be chained:
3957
\pythonil{3 < 4 < 5 < 6} is \pythonilIdx{True}, because \pythonil{3 < 4} and \pythonil{4 < 5} and \pythonil{5 < 6}.

0 commit comments

Comments
 (0)