hypot function

double hypot(
  1. num x,
  2. num y, [
  3. num? z
])

Computes the length of the hypotenuse sqrt(x^2 + y^2).

Optionally computes the 3D magnitude sqrt(x^2 + y^2 + z^2) if z is provided. Avoids intermediate overflow and underflow common with raw x*x + y*y. Corresponds to std::hypot from C++11 (2 args) / C++17 (3 args).

Implementation

double hypot(num x, num y, [num? z]) {
  final dx = x.abs().toDouble();
  final dy = y.abs().toDouble();
  final dz = z?.abs().toDouble() ?? 0.0;

  final maxVal = math.max(dx, math.max(dy, dz));
  if (maxVal == 0.0) return 0.0;

  final cx = dx / maxVal;
  final cy = dy / maxVal;
  final cz = dz / maxVal;

  return maxVal * math.sqrt(cx * cx + cy * cy + cz * cz);
}