Why 2/5 print 0.400000002 ???? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why 2/5 print 0.400000002 ????

why print(2/5) output 0.4000000002 but not 0.4? I know is 2/5 == 0.4,but how can I get 0.4 not 0.400000000002 help

6th Apr 2017, 2:50 AM
黑墨水鱼
黑墨水鱼 - avatar
2 Answers
+ 4
Binary represents 0 and positive integers. For negative integers, storage 'steals' the leftmost bit to represent 'plus' or 'minus'. Fractions steal even more bits, causing storage to record a 'mantissa' and 'exponent'...which have to be combined to approximate your answer. You type: >>> x=2/5 but the computer records a binary fraction: >>> x.as_integer_ratio() (3602879701896397, 9007199254740992) 36.../90.... an integer over a power of 2... = about 0.4 Finally, how to get 0.4: >>> format(x, '.2f') '0.40' Just remember it's a display trick.
6th Apr 2017, 11:25 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
computers are not good with floating point numbers. it can not get .4 exactly. normally the closest it can get is like .3999999999999 if you want .4, find a function that will cut it to 1 decimal place for you
6th Apr 2017, 2:51 AM
Edward