floating point - Why does python show 0.2 + 0.2 as 0.4? -


i think understood why 0.1 + 0.2 0.30000000000000004, following same logic why 0.2 + 0.2 = 0.4? isn't 0.2 value can't in binary base? thank time.

to 0.2 need sum binary fractions of 2. here first few:

decimal   binary 1       = 1 0.5     = 0.1 0.25    = 0.01 0.125   = 0.001 0.0625  = 0.0001 

so, 0.2, need sum

0.125 + 0.0625 = 0.187500 

the next binary fraction 0.03125. if sum that, it's large (> 0.2), next 1 0.015625. following one, 0.0078125 ok, so

0.125 + 0.0625 + 0.0078125 = 0.195312 

and on. have skipped 0.5 (gives 0), , 0.25 (another 0), did use 0.125 (1) , 0.0625 (1). again, skipped 2 values (00) , used next 1 (1)...

but, whatever do, cannot represent 0.2 exact binary numner. have continue , continue... if don't continue infinitely, representation not 0.2...

now try 0.25 or 0.25...

now why seeing different things in modern pythons (>= 2.7, , >= 3), comes internal change:

in versions prior python 2.7 , python 3.1, python rounded value 17 significant digits, giving ‘0.10000000000000001’. in current versions, python displays value based on shortest decimal fraction rounds correctly true binary value, resulting in ‘0.1’.

see this article, bottom of page.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -