0

Value error due to improper storing of float value

Computers can't store floats perfectly accurately, in the same way that we can't write down the complete decimal expansion of 1/3 (0.3333333333333333...). Keep this in mind, because it often leads to infuriating bugs! How do we avoid above bugs and how to find the accurate decimal value. eg: length = int(input("Enter Length:")) diameter = int(input("Enter Diameter:")) Total_Volume = int(input("Enter Total volume:")) Radius = diameter/2 r=round(Radius,1) Volume_1_cargo = (1.3333)*3.14*(r**3) Volume_cargo = round(Volume_1_cargo,2) volume_container = length**3 total_volume_spent = Volume_cargo*Total_Volume remaining_volume = volume_container-total_volume_spent print ("{0:.2f}".format(remaining_volume)) For above code my result should be : 4981.58 But am getting 4981.54 Enter Length:18 Enter Diameter:5 Enter Total volume:13 4981.54 Kindly help how to overcome these sort of issues

22nd Sep 2019, 1:52 AM
Durga
2 Réponses
0
There is no fix for that, it's an error related to how numbers are represented, for example: 0.1+0.1+0.1=0.3000000000004 what you can do is try to multiply the values, then divide them again, for example: (0.1*10+0.1*10+0.1*10)/10=0.3 So you have to think of a formula that will leave your number big enought to be divided accuratly, then divide the big result again But it's really difficult to try and fix it, for example: 0.3 = 0.3, but 0.3+5-5 =0.29999999999998
22nd Sep 2019, 2:09 AM
Aymane Boukrouh
Aymane Boukrouh - avatar
0
A difference of 0.04 is quite insignificant, but if you want to get 4981.58 as the result, don't round the value of "Volume_1_cargo". Volume_cargo = Volume_1_cargo
22nd Sep 2019, 2:52 AM
Diego
Diego - avatar