cbrt function

The cube root of x, to the precision of JavaScript's Math.cbrt.

Dart has no cbrt. pow(x, 1 / 3) is close but can be a couple of units in the last place out, which is enough to flip an 8-bit rounding boundary. One Newton–Raphson step on the result recovers the accuracy.

Implementation

@visibleForTesting
double cbrt(double x) {
  if (x == 0 || !x.isFinite) return x;
  final negative = x < 0;
  final magnitude = negative ? -x : x;
  var r = math.pow(magnitude, 1 / 3) as double;
  r -= (r - magnitude / (r * r)) / 3;
  return negative ? -r : r;
}