+ 2

Can you explain?

I was messing around with floats, then I saw that 0.1+0.2 made something other than 0.3. Why?

29th Jan 2021, 9:24 AM
Chin Serng Siew
Chin Serng Siew - avatar
4 odpowiedzi
+ 7
Floating point arithmetic has built-in problems as it's based on a binary approximation of numbers. Explained here: https://docs.python.org/3/tutorial/floatingpoint.html If you want to get just 0.3, just use round() function: round( 0.1+0.2, 1 ) round( num, round_place)
29th Jan 2021, 9:28 AM
noteve
noteve - avatar
+ 2
What happens can be compared to the problems you face when you want to express 1/3 or 1/7 as decimal number like 0.333... or 0.142... with a limited number of digits: You have to truncate somewhere. The best you can do is minimize the deviation by proper rounding. But there is no exact representation
29th Jan 2021, 10:38 AM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 1
Ok
27th Jun 2021, 5:29 AM
Chin Serng Siew
Chin Serng Siew - avatar