Python: 50*1.1 = 55.0000000001? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python: 50*1.1 = 55.0000000001?

See the code below. I suspect there are other similar cases. Due to the trailing decimal, certain calculations become tricky and somewhat unpredictable . E.g. math.ceil(50*1.1) turns out to be 56, which is incorrect. My questions: 1. Under what circumstances should I expect this type of cases to occur? 2. What's the best way to deal with this? Thanks. https://code.sololearn.com/c6ywYjHUGjKW/?ref=app

25th Jul 2023, 5:00 AM
El Johnson
3 Answers
+ 9
The error is caused by floating point arithmetics and is a known problem. Is the precision relevant for your purposes? If your answer is 'yes' then you should get familiar with the 'decimal'-module. This is especially e.g. for calculations in the financial sector which has high precision demands. To solve these and similar tasks, many universities offering computer science programs have an "Institute for Fault Tolerance." If not, then the field of study is integrated into another institute. This shows that this is a steady field of scientific research.
25th Jul 2023, 5:13 AM
Jan Markus
+ 4
It is inherent to how computers represent numbers, hence it is not quite an error. Floats should not be compared with "==", unless taking floating point limitations into consideration. https://www.sololearn.com/Discuss/3226502/?ref=app
25th Jul 2023, 9:36 AM
Lisa
Lisa - avatar
0
Thank you. Very informative.
25th Jul 2023, 11:54 AM
El Johnson