Number bug, calculation is wrong - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Number bug, calculation is wrong (/thread-20711.html) |
Number bug, calculation is wrong - d3fi - Aug-26-2019 so here is my code elif im.lower() in ("inh, inhalation, inhala"): # inhalation barn = (input("Barn eller voksen? ")) if barn.lower() in ("voksen", "vok"): # to adults print("1 mg blandes op i 2 ml saltvand og gives på nebulisator") elif barn.lower() in ("barn", "ba", "bar"): # to child vaegt = int(input("Hvad vejer barnet? ")) inhalation = vaegt * 0.1 #Here is what should be calculated if inhalation > 1: print("1 mg blandes op i 2 ml saltvand og gives på nebulisator") else: print(inhalation, "mg blandes op i 2 ml saltvand og gives på nebulisator") #This is broken, i think.if you type in "7" in line 6, the output will be 0.7000000000000001. it just needs to be 0.7. why does it do that? i am writing in JetBrains pycharm RE: Number bug, calculation is wrong - jefsummers - Aug-26-2019 https://docs.python.org/3/tutorial/floatingpoint.html Floating point is an approximation. Remember we are working with base 2. The above has a nice discussion of floating point and the inherent errors, in any programming language, of using it. RE: Number bug, calculation is wrong - perfringo - Aug-27-2019 Python has built-in module decimal which purpose defined as: "The decimal module provides support for fast correctly-rounded decimal floating point arithmetic." >>> import decimal >>> decimal.getcontext().prec = 2 # set precision to 2 (default is 28) >>> vaegt = decimal.Decimal(input("Hvad vejer barnet? ")) Hvad vejer barnet? 7 >>> inhalation = vaegt * decimal.Decimal(0.1) >>> print(inhalation) 0.70 >>> inhalation Decimal('0.70')It's important to note: Quote:The significance of a new Decimal is determined solely by the number of digits input. Context precision and rounding only come into play during arithmetic operations. This means that: >>> decimal.Decimal(7 * 0.1) Decimal('0.70000000000000006661338147750939242541790008544921875') >>> decimal.Decimal(7) * decimal.Decimal(0.1) Decimal('0.70') |