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

g.peterh...@t-online.de changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |g.peterh...@t-online.de

--- Comment #11 from g.peterh...@t-online.de ---
Would this be a good implementation for hypot3 in cmath?

#define GCC_UNLIKELY(x) __builtin_expect(x, 0)
#define GCC_LIKELY(x) __builtin_expect(x, 1)

namespace __detail
{
        template <typename _Tp>
        inline _GLIBCXX_CONSTEXPR typename
enable_if<is_floating_point<_Tp>::value, bool>::type __isinf3(const _Tp __x,
const _Tp __y, const _Tp __z)   noexcept
        {
                return bool(int(std::isinf(__x)) | int(std::isinf(__y)) |
int(std::isinf(__z)));
        }

        template <typename _Tp>
        inline _GLIBCXX_CONSTEXPR typename
enable_if<is_floating_point<_Tp>::value, _Tp>::type  __hypot3(_Tp __x, _Tp __y,
_Tp __z)     noexcept
        {
                __x = std::fabs(__x);
                __y = std::fabs(__y);
                __z = std::fabs(__z);

                const _Tp
                        __max = std::fmax(std::fmax(__x, __y), __z);

                if (GCC_UNLIKELY(__max == _Tp{}))
                {
                        return __max;
                }
                else
                {
                        __x /= __max;
                        __y /= __max;
                        __z /= __max;
                        return std::sqrt(__x*__x + __y*__y + __z*__z) * __max;
                }
        }
}       //      __detail


        template <typename _Tp>
        inline _GLIBCXX_CONSTEXPR typename
enable_if<is_floating_point<_Tp>::value, _Tp>::type  __hypot3(const _Tp __x,
const _Tp __y, const _Tp __z)   noexcept
        {
                return (GCC_UNLIKELY(__detail::__isinf3(__x, __y, __z))) ?
numeric_limits<_Tp>::infinity() : __detail::__hypot3(__x, __y, __z);
        }

#undef GCC_UNLIKELY
#undef GCC_LIKELY

How does it work?
* Basically, I first pull out the special case INFINITY (see
https://en.cppreference.com/w/cpp/numeric/math/hypot).
* As an additional safety measure (to prevent misuse) the functions are defined
by enable_if.

constexpr
* The hypot3 functions can thus be defined as _GLIBCXX_CONSTEXPR.

Questions
* To get a better runtime behavior I define GCC_(UN)LIKELY. Are there already
such macros (which I have overlooked)?
* The functions are noexcept. Does that make sense? If yes: why are the math
functions not noexcept?

thx
Gero

Reply via email to