Skip to content

Minor optimization for integer conversion to double #40557

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions src/sage/rings/integer.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -7813,11 +7813,6 @@ cdef double mpz_get_d_nearest(mpz_t x) except? -648555075988944.5:
# to have 54 bits remaining.
cdef mp_bitcnt_t shift = sx - 54

# Compute q = trunc(x / 2^shift) and let remainder_is_zero be True
# if and only if no truncation occurred.
cdef int remainder_is_zero
remainder_is_zero = mpz_divisible_2exp_p(x, shift)

sig_on()

cdef mpz_t q
Expand All @@ -7842,12 +7837,16 @@ cdef double mpz_get_d_nearest(mpz_t x) except? -648555075988944.5:
# Round towards zero
pass
else:
if not remainder_is_zero:
# Remainder is nonzero: round away from zero
if (q64 & 2) == 2:
# round to even and round away from zero gives the same result, no need to check
q64 += 1
else:
# Halfway case: round to even
q64 += (q64 & 2) - 1
if mpz_divisible_2exp_p(x, shift):
# Halfway case: round to even
q64 -= 1
else:
# Remainder is nonzero: round away from zero
q64 += 1

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