Skip to content

Commit

Permalink
[libc][NFC] Simplify logic in sqrt (#80426)
Browse files Browse the repository at this point in the history
  • Loading branch information
gchatelet authored Feb 2, 2024
1 parent 3050311 commit b629414
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 22 deletions.
17 changes: 6 additions & 11 deletions libc/src/__support/FPUtil/generic/sqrt.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,21 +78,16 @@ LIBC_INLINE cpp::enable_if_t<cpp::is_floating_point_v<T>, T> sqrt(T x) {

FPBits_t bits(x);

if (bits.is_inf_or_nan()) {
if (bits.is_neg() && (bits.get_mantissa() == 0)) {
// sqrt(-Inf) = NaN
return FLT_NAN;
} else {
// sqrt(NaN) = NaN
// sqrt(+Inf) = +Inf
return x;
}
} else if (bits.is_zero()) {
if (bits == FPBits_t::inf(Sign::POS) || bits.is_zero() || bits.is_nan()) {
// sqrt(+Inf) = +Inf
// sqrt(+0) = +0
// sqrt(-0) = -0
// sqrt(NaN) = NaN
// sqrt(-NaN) = -NaN
return x;
} else if (bits.is_neg()) {
// sqrt( negative numbers ) = NaN
// sqrt(-Inf) = NaN
// sqrt(-x) = NaN
return FLT_NAN;
} else {
int x_exp = bits.get_exponent();
Expand Down
17 changes: 6 additions & 11 deletions libc/src/__support/FPUtil/generic/sqrt_80_bit_long_double.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,21 +43,16 @@ LIBC_INLINE long double sqrt(long double x) {

LDBits bits(x);

if (bits.is_inf_or_nan()) {
if (bits.is_neg() && (bits.get_mantissa() == 0)) {
// sqrt(-Inf) = NaN
return LDNAN;
} else {
// sqrt(NaN) = NaN
// sqrt(+Inf) = +Inf
return x;
}
} else if (bits.is_zero()) {
if (bits == LDBits::inf(Sign::POS) || bits.is_zero() || bits.is_nan()) {
// sqrt(+Inf) = +Inf
// sqrt(+0) = +0
// sqrt(-0) = -0
// sqrt(NaN) = NaN
// sqrt(-NaN) = -NaN
return x;
} else if (bits.is_neg()) {
// sqrt( negative numbers ) = NaN
// sqrt(-Inf) = NaN
// sqrt(-x) = NaN
return LDNAN;
} else {
int x_exp = bits.get_explicit_exponent();
Expand Down

0 comments on commit b629414

Please sign in to comment.