-1

why print(2 == 2.) returns True

As per my understanding 2 is integer and 2.0 is float. They both are stored differently in memory.

I think it is returning True because they both belong to same class that is integer class?

I have gone through similar stack overflow question but concept is still not clear to me. Can someone please explain?

1

2 Answers 2

1

Memory representation doesn't really have anything to do with it (or at least, it doesn't prevent certain integers from comparing equal to equivalent real numbers).

2 == 2. is implemented by int.__eq__(2, 2.), which is defined to handle integer/float comparisons by making appropriate type conversions. Since int is a "narrower" type than float, 2 is first converted to a floating point value. (As an implementation detail, I suspect this is done by int.__eq__ calling float.__eq__(2., 2) and the conversion is done there, rather than the int type knowing any particular details about how floating-point values are represented.)

Note that not every int can be represent exactly as a floating-point value, as int uses arbitrary precision but float is fixed. For example, on my machine

>>> 2000000000000000000000000000000000 == 2000000000000000000000000000000000.
False

(I copy-pasted the integer to produce the floating-point literal, so the 0s line up.)

Sign up to request clarification or add additional context in comments.

Comments

0

This depends on how python implements the equality operator between float and int. I would imagine that in this case the int is cast to float before performing the comparison under the hood.

7 Comments

It's not implementation-dependent, it's specified by the language. See the linked question.
It's implementation-dependent in the sense that Python doesn't specify any particular implemantion of floating-point values; it leaves it up to the machine's native type.
@chepner: The Python 3 documentation says “A comparison between numbers of different types behaves as though the exact values of those numbers were being compared.” So the floating-point type is irrelevant; an integer number and a floating-point number will compare equal if and only if they represent the same value, regardless of what values either type can represent. (It is possible that the floating-point
How is the floating-point type irrelevant to the set of values it can represent?
The problem is that not every floating-point literal produces a unique floating-point value. Consider something like 2000000000000000000000000000001. == 2000000000000000000000000000002.. You could get True or False, depending on how much precision your underlying floating-point representation has available to store the mantissa.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.