0

In python, Why does the decimal representation of same number shows to occupy lesser space in memory(almost half)?

sys.getsizeof(1234561111111111111111111111111111111111111112223567744.0)
24
sys.getsizeof(1234561111111111111111111111111111111111111112223567744)
48
Carrot
  • 376
  • 5
  • 9

1 Answers1

2

This is not specific to Python 2.7, you would get the same with Python 3.

Your two numbers are not the same: the first one is a float, that will be stored as a float (and so rounded), and will use the same number of bytes whatever its value (in the allowed range for floats):

a = 1234561111111111111111111111111111111111111112223567744.0
>>> a
1.2345611111111112e+54

while the second one is an integer, which will be stored with unlimited precision (all digits are kept):

b = 1234561111111111111111111111111111111111111112223567744
>>> b
1234561111111111111111111111111111111111111112223567744

The size needed to store it will grow without limit with the number of digits.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • When you say first one will be stored as float and rounded, is there a size/length limit to this as for smaller float/decimal numbers, I don't think there is any rounding off happening. – Carrot Nov 09 '19 at 17:49
  • I have updated the question.Is there a way to get this back to float because below produces a different number entirely. `a=1234561111111111111111111111111111111111111112223567744.01 print( "%.2f" % float(str(a))) 1234561111109999993203066987989422162054126101852061696.00` – Carrot Nov 09 '19 at 17:51
  • Floats have limited precision (have a look at https://stackoverflow.com/questions/588004/is-floating-point-math-broken for more details), so there is no way you can have a float represented exactly with that many digits. What is stored is the nearest representable value, not the one you entered. You could have a look at the [decimal](https://docs.python.org/3.8/library/decimal.html) module if you want an exact representation of decimal numbers. – Thierry Lathuille Nov 09 '19 at 17:53