Skip to content

diffOfProducts

diffOfProducts(a, b, c, d): number

Defined in: diff-of-products.ts:31

a * b - c * d, accurate to within 1.5 units in the last place of the true result however badly the two products cancel.

Kahan’s algorithm for the 2×2 determinant. Written naively, the expression rounds each product to 53 bits and then subtracts them: when they very nearly cancel, every surviving bit of the answer comes from the bits that rounding threw away, and the result can be wrong in sign or lose all precision. This recovers both rounding errors first and folds them back in.

It is the right tool wherever the term count is fixed and small — 2×2 determinants, cross products, intersection denominators, orientation predicates, complex and quaternion products, discriminants. For a variable-length sum, reach for @ac-kit/core’s PreciseSum or sumPrecise instead; and for a variable-length sum of products, use both — this per term, that for the total.

Measured at 9.7 ns against the naive expression’s 2.0 ns on V8 — 4.9× the cost, all of it branch-free and allocation-free. Cheap enough for a predicate, worth measuring before putting it in a per-element loop.

number

First factor of the positive product.

number

Second factor of the positive product.

number

First factor of the negative product.

number

Second factor of the negative product.

number

a * b - c * d.