why is epsilon used when comparing 'double' or 'float' numbers?

Status
Not open for further replies.

electroRF

Member
Hi,
I see in many code samples that to compare to double or float numbers,
they don't perform: a == b
they instead perform: abs(a - b) < epsilon

Why is that?

both a and b are of the same machine, therefore have the same percision, so why is epsilon needed?

Thanks.
 
Great question!!!! as i am trying to learn maths, can someone explain what epsilon is and it's symbol please, and also if i can be cheeky ask for a worked example of the above equation, many many thanks
 
Floating numbers often cannot represent the exact entities. For example, 1/3 cannot be presented exactly, and will be a number either a little bit less than 1/3, or a little bit more. Therefore, there's an error in floating point representations. During calculations, this error accumulates and may become quite substantial (something to think about when you do extensive floating point calculations). Because of this error, you often cannot count that the floating point numbers are exactly equal. For example 1/3 + 1/3 + 1/3 = 1, but when you sum up 1/3 + 1/3 + 1/3 with floating operations, the result will be slightly different from 1, and (a == b) will evaluate to false. Therefore, you use the other form - (abs(a - b) < epsilon) - which will be true even if there's a light difference between a and b. epsilon is a measure of how much difference you want to tolerate. With long calculations, you would use higher values of epsilon because the potential error is higher.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…