Skip to content

Commit b631411

Browse files
committed
[libc] specially handle po2 cases
Signed-off-by: Shreeyash Pandey <[email protected]>
1 parent 31bbc8b commit b631411

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

libc/src/__support/fixed_point/fx_bits.h

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -281,11 +281,18 @@ template <typename XType> LIBC_INLINE constexpr XType divi(int n, int d) {
281281
// to quadratic convergence. So,
282282
// E1 = (0.059)^2 = 0.0034
283283
long accum val = nrstep(d_scaled_val, initial_approx);
284-
// E2 = 0.0000121
285-
val = nrstep(d_scaled_val, val);
286-
// E3 = 1.468e−10
287-
val = nrstep(d_scaled_val, val);
288-
284+
auto isPowerOfTwo = [](int n) { return (n > 0) && ((n & (n - 1)) == 0); };
285+
// Division with a power of 2 would generally be expected to be
286+
// exact, we handle this by specially treating po2 cases and having
287+
// extra iterations for them.
288+
if (FXRep<XType>::FRACTION_LEN > 8 || isPowerOfTwo(cpp::abs(d))) {
289+
// E2 = 0.0000121
290+
val = nrstep(d_scaled_val, val);
291+
if (FXRep<XType>::FRACTION_LEN > 16 || isPowerOfTwo(cpp::abs(d))) {
292+
// E3 = 1.468e−10
293+
val = nrstep(d_scaled_val, val);
294+
}
295+
}
289296
long accum res = n_scaled_val * val;
290297

291298
if (result_is_negative) {

0 commit comments

Comments
 (0)