Skip to content

Branchless algorithm for RuntimeLong.toDouble. #5204

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 2 commits into
base: main
Choose a base branch
from

Conversation

sjrd
Copy link
Member

@sjrd sjrd commented Jun 23, 2025

It turns out the computation we did in the non-negative case also works for the negative case. The proof relies on elementary properties of the two's complement representation.

I don't know how I never saw this before. To make things worse, it seems that Kotlin and J2CL knew all along, and I never realized when skimming their implementations either.


As a second commit, we introduce code paths for signed safe doubles, now that the conversions from signed longs to doubles is the same as the unsigned ones.

It turns out the computation we did in the non-negative case also
works for the negative case. The proof relies on elementary
properties of the two's complement representation.

I don't know how I never saw this before. To make things worse, it
seems that Kotlin and J2CL knew all along, and I never realized
when skimming through their implementations either.
@sjrd sjrd force-pushed the rt-long-to-double-much-simpler branch from 817e57a to 8d55e54 Compare June 23, 2025 13:07
@sjrd sjrd requested a review from gzm0 June 23, 2025 13:08
Since conversions of signed longs to doubles is in fact no more
expensive than the unsigned longs, we can take shorter paths for
values that fit in the *signed* safe range.

This applies to the conversions to string (including in the
javalib) and to float.

It could also apply to signed division and remainder. However,
benchmarks suggest that doing so makes it slower. The trouble is
that we then need a signed double-to-long conversion for the
result, and that appears to be slower than performing the 3 sign
adjustments.
@sjrd sjrd force-pushed the rt-long-to-double-much-simpler branch from 8d55e54 to 331baa8 Compare June 23, 2025 17:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant