https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121615

            Bug ID: 121615
           Summary: Function abs(complex<int>) does not compute correct
                    results
           Product: gcc
           Version: 14.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: chris21k at gmx dot de
  Target Milestone: ---

$ cat show_abs_bug.cpp
#include <complex>
#include <iostream>

int main() {
    std::cout << std::abs(std::complex<int>(3, -4)) << std::endl;       //
expected sqrt(3^2 + (-4)^2) = 5 and not 4
}
$ g++ show_abs_bug.cpp -o show_abs_bug
$ ./show_abs_bug
4
$ less /usr/include/c++/complex  # snippet
  // 26.2.7/3 abs(__z):  Returns the magnitude of __z.
  template<typename _Tp>
    inline _Tp
    __complex_abs(const complex<_Tp>& __z)
    {
      _Tp __x = __z.real();
      _Tp __y = __z.imag();
      const _Tp __s = std::max(abs(__x), abs(__y));
      if (__s == _Tp())  // well ...
        return __s;
      __x /= __s;
      __y /= __s;
      return __s * sqrt(__x * __x + __y * __y);
    }
$ g++ --version
g++ (Debian 14.2.0-19) 14.2.0
Copyright (C) 2024 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

cat /etc/issue
Debian GNU/Linux forky/sid \n \l

$ uname -a
Linux betty 6.12.38+deb13-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.12.38-1
(2025-07-16) x86_64 GNU/Linux


(The called) above abs implementation in header file <complex> imho seems to
only be correct for complex<"floating point"> but not for complex<"integral"> .
Either there is a bug in the detection which implementation should be called or
the above implementation should more general.
Btw. same behaviour with gcc 12.2.0 in Debian bookworm. Unfortunately, I have
no test with a newer gcc, sorry for that.

Many thanks,
Chris

Reply via email to