apple / swift-numerics

Advanced mathematical types and functions for Swift

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Pick semantics of `Complex` `.magnitude` property.

stephentyrone opened this issue · comments

Currently .magnitude uses the two-norm (sqrt(real*real + imag*imag)), because it's the most obvious choice, but we don't need to use it, and there are some good reasons why we should consider using either the 1-norm (|real| + |imag|) or ∞-norm (max(|real|, |imag|)) instead.

  • The two-norm requires special care to avoid spurious overflow/underflow, but the naive expressions for the 1-norm or ∞-norm are always correct.
  • Even when care is used, near the overflow boundary the two-norm may not be representable. The ∞-norm in particular is always representable (because of this, the ∞-norm would seem to be the obvious alternative; it gives the nicest API surface).
  • Both the 1-norm and ∞-norm are much easier to compute for operators than the 2-norm (O(n) vs. "no closed form expression, but usually O(n^3) iterative methods"), so it would be nice to establish a precedent of .magnitude binding one of these cheaper-to-compute norms.

Because Numeric doesn't specify the semantics, there's no problem changing what we do, but this is a change that would be good to make soon before too many people start using it. We should still provide the two-norm (because it's often useful), but we would simply do it under a different name (length, norm, euclideanNorm, etc).