Skip to content

Commit a879073

Browse files
authored
[libc][math] Fix a bug in cbrt when the result is rounded to the next exponent. (#113749)
1 parent 889b67c commit a879073

File tree

3 files changed

+11
-8
lines changed

3 files changed

+11
-8
lines changed

libc/src/math/generic/cbrt.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,10 +235,10 @@ LLVM_LIBC_FUNCTION(double, cbrt, (double x)) {
235235

236236
// Lambda function to update the exponent of the result.
237237
auto update_exponent = [=](double r) -> double {
238-
uint64_t r_m = FPBits(r).uintval() & 0x800F'FFFF'FFFF'FFFF;
238+
uint64_t r_m = FPBits(r).uintval() - 0x3FF0'0000'0000'0000;
239239
// Adjust exponent and sign.
240240
uint64_t r_bits =
241-
r_m | (static_cast<uint64_t>(out_e) << FPBits::FRACTION_LEN);
241+
r_m + (static_cast<uint64_t>(out_e) << FPBits::FRACTION_LEN);
242242
return FPBits(r_bits).get_val();
243243
};
244244

libc/test/src/math/cbrt_test.cpp

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,12 +87,13 @@ TEST_F(LlvmLibcCbrtTest, InDoubleRange) {
8787

8888
TEST_F(LlvmLibcCbrtTest, SpecialValues) {
8989
constexpr double INPUTS[] = {
90-
0x1.4f61672324c8p-1028, 0x1.00152f57068b7p-1, 0x1.006509cda9886p-1,
91-
0x1.018369b92e523p-1, 0x1.10af932ef2bf9p-1, 0x1.1a41117939fdbp-1,
92-
0x1.2ae8076520d9ap-1, 0x1.a202bfc89ddffp-1, 0x1.a6bb8c803147bp-1,
93-
0x1.000197b499b1bp+0, 0x1.00065ed266c6cp+0, 0x1.d4306c202c4c2p+0,
94-
0x1.8fd409efe4851p+1, 0x1.95fd0eb31cc4p+1, 0x1.7cef1d276e335p+2,
95-
0x1.94910c4fc98p+2, 0x1.a0cc1327bb4c4p+2, 0x1.e7d6ebed549c4p+2,
90+
0x1.4f61672324c8p-1028, -0x1.fffffffffffffp-1021, 0x1.00152f57068b7p-1,
91+
0x1.006509cda9886p-1, 0x1.018369b92e523p-1, 0x1.10af932ef2bf9p-1,
92+
0x1.1a41117939fdbp-1, 0x1.2ae8076520d9ap-1, 0x1.a202bfc89ddffp-1,
93+
0x1.a6bb8c803147bp-1, 0x1.000197b499b1bp+0, 0x1.00065ed266c6cp+0,
94+
0x1.d4306c202c4c2p+0, 0x1.8fd409efe4851p+1, 0x1.95fd0eb31cc4p+1,
95+
0x1.7cef1d276e335p+2, 0x1.94910c4fc98p+2, 0x1.a0cc1327bb4c4p+2,
96+
0x1.e7d6ebed549c4p+2,
9697
};
9798
for (double v : INPUTS) {
9899
double x = FPBits(v).get_val();

libc/test/src/math/smoke/cbrt_test.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,6 @@ TEST_F(LlvmLibcCbrtTest, SpecialNumbers) {
3232
EXPECT_FP_EQ_ALL_ROUNDING(-0x1.0p42, LIBC_NAMESPACE::cbrt(-0x1.0p126));
3333
EXPECT_FP_EQ_ALL_ROUNDING(0x1.0p341, LIBC_NAMESPACE::cbrt(0x1.0p1023));
3434
EXPECT_FP_EQ_ALL_ROUNDING(-0x1.0p341, LIBC_NAMESPACE::cbrt(-0x1.0p1023));
35+
EXPECT_FP_EQ(-0x1.0p-340, LIBC_NAMESPACE::cbrt(-0x1.fffffffffffffp-1021));
36+
EXPECT_FP_EQ(2.0, LIBC_NAMESPACE::cbrt(0x1.fffffffffffffp2));
3537
}

0 commit comments

Comments
 (0)