On 25/11/2016 11:24, Nikunj wrote:
Out of curiosity, I wanted to understand the reason behind having different
memory location for two identical floats . This is unlike ints or strings.
Tried googling but couldn't find anything concrete. Any links or references
would be appreciated!
Do you mean for identical floating point literals?
Some implementations will do that; see the test below. Here, Py2 and Py3
both give the same id for 1.3, but not for a runtime-derived 1.3. Pypy
will give the same id even for 1.3 at runtime (although I suspect it can
see past my simple expression and reduce it to 1.3).
Doing this is harder for floats than for integers. So if it is decided
to have integer values 0 to 1000 as shared objects, then it is easy to
have a lookup table of 1001 objects so as to avoid repeatedly creating
and destroying millions of small integers.
But how many floats are there between 0.0 and 1000? Billions I think,
and the bit-pattern for 1.3 might be 0x3ff4cccccccccccd which doesn't
lend itself to a simple lookup.
----------------------
print ("Floats:")
x=1.3
y=1.3
print (id(x))
print (id(y))
print (x is y)
z=x+1.3-y
print (id(z))
print (x-z)
print (x==z)
print (x is z)
print ("")
print ("Integers:")
x=13
y=13
print (id(x))
print (id(y))
print (x is y)
z=x+13-y
print (id(z))
print (x-z)
print (x==z)
print (x is z)
--
Bartc
--
https://mail.python.org/mailman/listinfo/python-list