Skip to content

Commit d40e29a

Browse files
author
Release Manager
committed
sagemathgh-40557: Minor optimization for integer conversion to double ``` x = 2^553 %timeit float(x) before: 114 ns ± 4.77 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) after: 106 ns ± 0.827 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) ``` just avoid calling the function unless absolutely needed. ### 📝 Checklist <!-- Put an `x` in all the boxes that apply. --> - [ ] The title is concise and informative. - [ ] The description explains in detail what this PR is about. - [ ] I have linked a relevant issue or discussion. - [ ] I have created tests covering the changes. - [ ] I have updated the documentation and checked the documentation preview. ### ⌛ Dependencies <!-- List all open PRs that this PR logically depends on. For example, --> <!-- - sagemath#12345: short description why this is a dependency --> <!-- - sagemath#34567: ... --> URL: sagemath#40557 Reported by: user202729 Reviewer(s): Travis Scrimshaw
2 parents a1c97da + 490c39c commit d40e29a

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

src/sage/rings/integer.pyx

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7813,11 +7813,6 @@ cdef double mpz_get_d_nearest(mpz_t x) except? -648555075988944.5:
78137813
# to have 54 bits remaining.
78147814
cdef mp_bitcnt_t shift = sx - 54
78157815

7816-
# Compute q = trunc(x / 2^shift) and let remainder_is_zero be True
7817-
# if and only if no truncation occurred.
7818-
cdef int remainder_is_zero
7819-
remainder_is_zero = mpz_divisible_2exp_p(x, shift)
7820-
78217816
sig_on()
78227817

78237818
cdef mpz_t q
@@ -7842,12 +7837,16 @@ cdef double mpz_get_d_nearest(mpz_t x) except? -648555075988944.5:
78427837
# Round towards zero
78437838
pass
78447839
else:
7845-
if not remainder_is_zero:
7846-
# Remainder is nonzero: round away from zero
7840+
if (q64 & 2) == 2:
7841+
# round to even and round away from zero gives the same result, no need to check
78477842
q64 += 1
78487843
else:
7849-
# Halfway case: round to even
7850-
q64 += (q64 & 2) - 1
7844+
if mpz_divisible_2exp_p(x, shift):
7845+
# Halfway case: round to even
7846+
q64 -= 1
7847+
else:
7848+
# Remainder is nonzero: round away from zero
7849+
q64 += 1
78517850

78527851
# The conversion of q64 to double is *exact*.
78537852
# This is because q64 is even and satisfies 2^53 <= q64 <= 2^54.

0 commit comments

Comments
 (0)