diff --git a/include/xsimd/arch/common/xsimd_common_math.hpp b/include/xsimd/arch/common/xsimd_common_math.hpp index b9484fa81..daa93799b 100644 --- a/include/xsimd/arch/common/xsimd_common_math.hpp +++ b/include/xsimd/arch/common/xsimd_common_math.hpp @@ -2034,17 +2034,25 @@ namespace xsimd * ==================================================== */ template - XSIMD_INLINE batch pow(batch const& self, batch const& other, requires_arch) noexcept + XSIMD_INLINE batch pow(batch base, batch exponent, requires_arch) noexcept { using batch_type = batch; const auto zero = batch_type(0.); - auto negself = self < zero; - auto iszeropowpos = self == zero && other >= zero; - auto adj_self = select(iszeropowpos, batch_type(1), abs(self)); - batch_type z = exp(other * log(adj_self)); - z = select(iszeropowpos, zero, z); - z = select(is_odd(other) && negself, -z, z); - auto invalid = negself && !(is_flint(other) || isinf(other)); + const auto one = batch_type(1.); + const auto infinite_exponent = isinf(exponent); + // x^(+/-0), 1^y, and (-1)^(+/-inf) all evaluate to 1. + const auto unit_result = exponent == zero || base == one || (base == -one && infinite_exponent); + if (any(unit_result)) + { + base = select(unit_result, one, base); + exponent = select(unit_result, zero, exponent); + } + const auto zero_to_positive = base == zero && exponent > zero; + const auto magnitude = select(zero_to_positive, one, abs(base)); + auto z = select(zero_to_positive, zero, exp(exponent * log(magnitude))); + const auto negative_base = base < zero; + z = select(is_odd(exponent) && negative_base, -z, z); + const auto invalid = negative_base && !(is_flint(exponent) || infinite_exponent); return select(invalid, constants::nan(), z); } diff --git a/test/test_power.cpp b/test/test_power.cpp index de2ed14ff..624f2950a 100644 --- a/test/test_power.cpp +++ b/test/test_power.cpp @@ -108,7 +108,14 @@ struct power_test } #endif } + CHECK(xsimd::all(pow(batch_type(0), batch_type(0)) == batch_type(1))); #ifndef __FAST_MATH__ + const auto nan = std::numeric_limits::quiet_NaN(); + const auto inf = std::numeric_limits::infinity(); + CHECK(xsimd::all(pow(batch_type(nan), batch_type(0)) == batch_type(1))); + CHECK(xsimd::all(pow(batch_type(1), batch_type(nan)) == batch_type(1))); + CHECK(xsimd::all(pow(batch_type(-1), batch_type(inf)) == batch_type(1))); + // pow 0^-x { std::transform(zero_input.cbegin(), zero_input.cend(), rhs_input.cbegin(), expected.begin(),