Post · 2 min read· pp. 376–377

How and How Not to Compute a Relative Error

The relative error in a scalar yy as an approximation to a scalar xx is the absolute value of e=(x−y)/xe = (x-y)/x. I recently came across a program in which ee had been computed as 1−y/x1 - y/x. It had never occurred to me to compute it this way. The second version is slightly easier to type, requiring no parentheses, and it has the same cost of evaluation: one division and one subtraction. Is there any reason not to use this parenthesis-free expression?

Consider the accuracy of the evaluation, using the standard model of floating point arithmetic, which says that fl(xopy)=(xopy)(1+δ)fl(x \mathbin{\mathrm{op}} y) = (x \mathbin{\mathrm{op}} y)(1+\delta) with ∣δ∣≤u|\delta| \le u, where op\mathrm{op} is any one of the four elementary arithmetic operations and uu is the unit roundoff. For the expression e1=(x−y)/xe_1 = (x-y)/x we obtain, with a hat denoting a computed quantity,

e1^=(x−yx)(1+δ1)(1+δ2),∣δi∣≤u,i=1,2.\widehat{e_1} = \displaystyle\left(\frac{x-y}{x}\right) (1+\delta_1)(1+\delta_2), \qquad |\delta_i| \le u, \quad i = 1, 2.

It follows that

∣e−e1^e∣≤2u+u2.\left| \displaystyle\frac{e - \widehat{e_1}}{e} \right| \le 2u + u^2.

Hence e1e_1 is computed very accurately.

For the alternative expression, e2=1−y/xe_2 = 1 - y/x, we have

e2^=(1−yx(1+δ1))(1+δ2),∣δi∣≤u,i=1,2.\widehat{e_2} = \left(1 - \displaystyle\frac{y}{x}(1+\delta_1)\right) (1+\delta_2), \qquad |\delta_i| \le u, \quad i = 1, 2.

After a little manipulation we obtain the bound

∣e−e2^e∣≤u+∣1−ee∣(u+u2).\left| \displaystyle\frac{e - \widehat{e_2}}{e} \right| \le u + \left|\displaystyle\frac{1-e}{e}\right|(u + u^2).

The bound on the relative error in e2^\widehat{e_2} is of order ∣(1−e)/e∣u|(1-e)/e|u, and hence is very large when ∣e∣≪1|e| \ll 1.

To check these bounds we carried out a MATLAB experiment. For 500 single precision floating point numbers yy centered on x=3x = 3, we evaluated the relative error of yy as an approximation to xx using the two formulas. The results are shown in this figure, where an ideal error is of order u≈6×10−8u \approx 6\times 10^{-8}. (The MATLAB script that generates the figure is available as this gist.)

rel-err-formula.jpg

As expected from the error bounds, the formula 1−y/x1-y/x is very inaccurate when yy is close to xx, whereas (x−y)/x(x-y)/x retains its accuracy as yy approaches xx.

Does this inaccuracy matter? Usually, we are concerned only with the order of magnitude of an error and do not require an approximation with many correct significant figures. However, as the figure shows, for the formula ∣1−y/x∣|1-y/x| even the order of magnitude is incorrect for yy very close to xx. The standard formula ∣x−y∣/∣x∣|x-y|/|x| should be preferred.