Python Forum

Full Version: Number bug, calculation is wrong
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.
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')