Reputation: 89
So , for instance 4 can be represented as 00000100 in 8 bit and 4.0 can be represented in 8 bit as 01111000 using excess-4 notation and floating point notation. So they are not the same thing. However both Python and C gives 1 as the result when I compare 4 with 4.0 . How ? Aren't they suppossed to mean different things to do computer because of the reason I mentioned ?
Upvotes: 1
Views: 304
Reputation: 16184
I think your confusion is coming from the implicit type conversion which happens in both C and Python. In fact the Wikipedia page I linked to above uses the same form as your question, just with different numbers.
Other programming languages work differently. For example, in Rust or Haskell where there isn't any implicit type conversion then the compiler would complain and this code wouldn't compile. See an Rust example via Godbolt.
As a concrete demonstration of what a C compiler is doing, here is another example in godbolt. It shows an int
parameter being converted to a float
(via an fcvt
instruction) before a float comparison is performed (via feq
). Python does a similar thing but due to dynamic dispatch is a bit more complicated, the implementation is here and everything under the PyLong_Check
is handling the case of a float being compared to an integer.
Note that most data types don't directly compare the data as it's stored in memory. For example, IEEE 754 floats have two zeros (+1.0 and -1.0) but these compare as being equal to each other. Some languages allow you to compare raw bytes of memory, e.g. memcmp
in C, but this often isn't what you want to do.
Upvotes: 1
Reputation: 113
While it is true that those two values (4 and 4.0), represented in those binary forms can represent different 8 bit values, in comparison operations, Python and C compare the values of the inputs taking into consideration their respective types. This changes the behavior of the comparison drastically from a solely binary-reliant operation.
Python documentation states:
Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex. A comparison between numbers of different types behaves as though the exact values of those numbers were being compared
Thus, if you were to compare 4 to 4.0, it is treated as though the numbers were both the wider type, allowing for mixed arithmetic comparisons. As a result, considering 4 to be different from 4.0 in this situation, on the surface, is a bit misleading as the languages have specific behavior to compare them in a level manner.
Upvotes: 0