Skip to content

Commit

Permalink
Fix power function NaN handling so it returns NaN
Browse files Browse the repository at this point in the history
Summary: The C++ std::pow function returns 1 when 1 is raised to NaN. It returns NaN for every other number except for 1 which is strange. This change makes sure it will return NaN.

Differential Revision: D64145275
  • Loading branch information
Daniel Hunte authored and facebook-github-bot committed Oct 9, 2024
1 parent d5df0a7 commit eda5e37
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
4 changes: 3 additions & 1 deletion velox/functions/prestosql/Arithmetic.h
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,9 @@ struct PowerFunction {
template <typename TInput>
FOLLY_ALWAYS_INLINE void
call(double& result, const TInput& a, const TInput& b) {
result = std::pow(a, b);
result = std::isnan(a) || std::isnan(b)
? std::numeric_limits<double>::quiet_NaN()
: pow(a, b);
}
};

Expand Down
12 changes: 12 additions & 0 deletions velox/functions/prestosql/tests/ArithmeticTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,18 @@ TEST_F(ArithmeticTest, power) {
"pow(c0, c1)", baseDouble, exponentDouble, expectedDouble);
}

TEST_F(ArithmeticTest, powerNan) {
std::vector<double> baseDouble = {1, kNan};
std::vector<double> exponentDouble = {kNan, 1};
std::vector<double> expectedDouble = {kNan, kNan};

// Check using function name and alias.
assertExpression<double>(
"power(c0, c1)", baseDouble, exponentDouble, expectedDouble);
assertExpression<double>(
"pow(c0, c1)", baseDouble, exponentDouble, expectedDouble);
}

TEST_F(ArithmeticTest, powerInt) {
std::vector<int64_t> baseInt = {9, 10, 11, -9, -10, -11, 0};
std::vector<int64_t> exponentInt = {3, -3, 0, -1, 199999, 77, 0};
Expand Down

0 comments on commit eda5e37

Please sign in to comment.