Skip to content

Should Complex.magnitude use call to complex.abs instead of plain @sqrt? #23246

@DanikVitek

Description

@DanikVitek

Currently, the Complex.hypot uses a simple call to @sqrt, which is ok (and probably better?) for small numbers:

return @sqrt(self.re * self.re + self.im * self.im);
But there is already a dedicated function for calculating an absolute of a complex number, that references math.hypot:
/// Returns the absolute value (modulus) of z.
pub fn abs(z: anytype) @TypeOf(z.re, z.im) {
return math.hypot(z.re, z.im);
}
Which in turn states that it avoids unnecessary overflow and underflow:
/// Returns sqrt(x * x + y * y), avoiding unnecessary overflow and underflow.
///
/// Special Cases:
///
/// | x | y | hypot |
/// |-------|-------|-------|
/// | +-inf | any | +inf |
/// | any | +-inf | +inf |
/// | nan | fin | nan |
/// | fin | nan | nan |
pub fn hypot(x: anytype, y: anytype) @TypeOf(x, y) {

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions