Presentation is loading. Please wait.

Presentation is loading. Please wait.

Comparing floating point numbers

Similar presentations


Presentation on theme: "Comparing floating point numbers"— Presentation transcript:

1 Comparing floating point numbers
Decisions in Python Comparing floating point numbers

2 Comparing floating point numbers
Remember that floating point numbers are stored in a computer with some inevitable error If you are working with floats a lot in a program, you should be aware that your numbers may not be exactly what you think they are If you need to compare two floating point numbers (or float variables), it’s not a good idea to test for exact equality (==). Especially if one or both have been calculated (not input from the user), there may be enough difference between them that the == will not consider them equal!

3 How to deal with this? Most of the time you have an idea of how close is “good enough” to be considered equal. Suppose the margin is That is, if the two numbers are within of each other, then they can be considered ‘equal’ for your purposes. This can be coded pretty easily: if abs(x – y) <= 0.01: print(“good enough”)


Download ppt "Comparing floating point numbers"

Similar presentations


Ads by Google