-2

Am working on a small math-checker using Python and everything works well except of divisions. Problem: The quotient with two decimals (2/3 = 0.67), float, is equal to an input (0.67). But the if-statement I use to compare a user's input with the result says it isn't equal.

Assumption: the problem is related to float.

My code:

result = float(value0 / value1)
result = round(result,2)

value3 = input("Number 1")
value3 = float(value3)

if result != value3:
    print "Wrong!"
    print result
elif result == value:
    print "Right!"

Of course I could create a function with a different approach, but I am curious to understand why it doesn't work.

If there's a similar thread, please post the link and close this one. Thanks for any help.

canguru
  • 3
  • 2
  • 3
    But 2/3 isn't equal to 0.67. – kindall Apr 08 '16 at 16:52
  • I suggest using the `decimal ` module instead. https://docs.python.org/3/library/decimal.html#decimal.Decimal – Rick Apr 08 '16 at 16:55
  • Rick: Thanks for the link. kindall: I refer to the rounded result of 2/3 with two decimals. So I know that there's a difference between 0.666666... (or 2/3) and 0.67. – canguru Apr 10 '16 at 10:27

1 Answers1

1

when checking floats for equality always use

equal_threshold = 1e-5
if abs(result-value)<equal_threshold:
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179