Floating point, exactly
This library returns proven answers and so avoids floating-point arithmetic for its results. That makes it a good place to study floating point: every double is an exact rational number, Core can hold it, and so the rounding error of each operation is a number that can be computed exactly, not estimated.
exactOf(0.1); // 3602879701896397/36028797018963968 what the double 0.1 IS
floatParts(0.1, "0.1"); // sign, exponent, mantissa, bits, ulp, and the error against the 0.1 that was typed
floatOp("+", 0.1, 0.2); // { result: 0.30000000000000004, exact, error, relativeError, exactlyRepresentable: false }
roundoff("(1 - cos(x))/x^2", { x: 1e-8 });
// { float: 0, exact: [0.5, 0.5], relativeError: 1, digitsLost: 16, steps: […] }
These and the other numerical methods are also at @ratmath/analytic/methods.
What a double is
A double is with a 53-bit mantissa and an exponent (plus zero, subnormals, infinities and NaN). So it is a fraction whose denominator is a power of two. The decimal 0.1 is not such a fraction, and the double written 0.1 is the nearest one that is:
floatParts shows the three bit fields, the exact value, and the ulp: the gap to the next double. Rounding to nearest makes a relative error of at most , the unit roundoff.
One operation
IEEE arithmetic computes the exact result of on the two doubles and rounds it to the nearest double. floatOp gives both: exact is the true sum, difference, product or quotient of the two doubles as a rational, result is what the machine returns, and error is their exact difference. So stops being a mystery: the two inputs are each slightly above their decimals, their exact sum is not a double, and it rounds up.
Cancellation
Each operation is accurate to one part in . A calculation is not. Subtracting two nearly equal numbers gives a small result whose leading digits have cancelled, and the rounding errors already present in the inputs are then large in proportion. roundoff follows a whole formula both ways, in doubles and with certified enclosures of the true value at the same inputs, and lists every subexpression with its relative error. The step where the error jumps is the step to rewrite:
The two sides are equal; at the left gives 0 in doubles and the right gives 0.5, correct to the last bit.
| call | returns |
|---|---|
| exactOf(x) | the Rational equal to the double x |
| nearestDouble(q) | the double nearest a Rational, ties to even |
| floatParts(x, intended) | { sign, exponent, mantissa, bits, exact, ulp, next, previous, subnormal, intended, error, relativeError } |
| floatOp(op, a, b) | { result, exact, error, relativeError, exactlyRepresentable } |
| roundoff(formula, inputs) | { float, exact, error, relativeError, digitsLost, steps } |
@ratmath/analytic and Core's R, Rational, RationalInterval in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.