Mega Code Archive

 
Categories / Delphi / System
 

Avoiding Rounding Errors in Float Operations

Title: Avoiding Rounding Errors in Float Operations Question: Why do 2 variables containing the same float not appear to be equal? Answer: Floating Point variables of types Single, Double & Extended can suffer from Rounding problems. To illustrate, let us assume that we have a computer that works to 4 significant figures. Thus: 1 / 3 = 0.3333 Now we know that 3 * 1/3 = 1 but if we did: X := 1 / 3; X := X * 3; if X = 1 then // this would not be true Why? Because X = 0.9999 not 1. Computers do not have infinite decimal places. The Float types do give you better accuracy as you go from Single to Double to Extended but the above rounding errors persist. So rather than do Equality comparisons, we need to define how close is good enough. The following routines do this: var ESBTolerance: Extended = 0.00000001; // Set to the desired accuracy function SameFloat (const X1, X2: Extended): Boolean; begin Result := abs (X1 - X2) end; function FloatIsZero (const X: Extended): Boolean; begin Result := abs (X) end; function FloatIsPositive (const X: Extended): Boolean; begin Result := (X = ESBTolerance); end; function FloatIsNegative (const X: Extended): Boolean; begin Result := (X end;