0

For my assignment I have to check if a calculated value is within 0.05 of 0.5. To do this i thought subtracting one from another, taking the absolute value and checking if that is smaller or equal then 0.05 should do the trick. However when i try this piece of code.

x = abs(0.5 - 0.55)

if x <= 0.05:
    print 'x is', x, 'x = yes'
else:
    print 'x is', x, 'x = no'

y = abs(0.4 - 0.45)

if y <= 0.05:
    print 'y is', y, 'y = yes'
else:
    print 'y is', y, 'y = no'

The returns a very weird output.

x is 0.05 x = no
y is 0.05 y = yes

Where y is seen as 0.05 but x is not seen as 0.05, however both values are equal to 0.05 according to python. Am I doing something wrong?

Hans
  • 11
  • 1
  • check your conditions before you use them 0.5 - 0.55 Out[1]: -0.050000000000000044 – NaN Mar 03 '18 at 12:17

3 Answers3

1

By default it's generating long floating value

Try this:-

x = round(abs(0.5 - 0.55),2)
y = round(abs(0.4 - 0.45),2)
Narendra
  • 1,511
  • 1
  • 10
  • 20
  • This works thanks! But still why does the code I wrote work with 0.4 - 0.45, but not with 0.5 - 0.55? Shouldn't they both have a long floating value – Hans Mar 03 '18 at 12:20
  • @Hans it worked both r printing true i hope you r familiar with round right...that simple make it round that's it...and hope both output u r getting true right... – Narendra Mar 03 '18 at 12:26
  • 1
    @Hans 0.4 - 0.45 = 0.04999999.... which is approximated to 0.05 by Python. Hence you got it worked. – Austin Mar 03 '18 at 12:29
1
>>> x = abs(0.5 - 0.55)
>>> x
0.050000000000000044
>>> y = abs(0.4 - 0.45)
>>> y
0.04999999999999999

This is just how floats behave. Most programming languages are like this. Usually when comparing floats, its safer to check whether within an allowed error of your value, instead of checking for equality:

>>> x = abs(0.5 - 0.55)
>>> allowed_error = 0.000001
>>> abs(x - 0.05) <= allowed_error
True

Python3.5 adds the relevant math.isclose.

Sean Breckenridge
  • 1,932
  • 16
  • 26
0

I would use Decimal in this manner:

from decimal import Decimal
x1 = abs(0.5 - 0.55)
x2 = Decimal(abs(0.5 - 0.55)).quantize(Decimal(10) ** -2)

print (x1)
print (x2)

Output:

0.050000000000000044
Decimal('0.05')

Then your tests will work fine.

Tom
  • 44
  • 4