You have a line with two endpoints a
and b
(0 ≤ a < b
) on a 1D space. When a
or b
has a fractional value, you want to round it to an integer.
One way to do this is to round a
and b
each to its nearest integer, but this has a problem that the length of the rounded range (L
) can vary while b - a
stays the same. For example,
b - a = 1.4
(a, b) = (1, 2.4) -> (1, 2), L = 1
(1.2, 2.6) -> (1, 3), L = 2
We want to find a way to round (a, b)
so that L
always has the same value ⌊b - a⌋
while the rounded pair (ra, rb)
is closest to (a, b)
.
With (a, b) = (1.2, 2.6)
, we can consider two candidates of (ra, rb)
with L = ⌊2.6 - 1.2⌋ = 1
. One is (1, 2)
and the other is (2, 3)
. (1, 2)
's overlapping range with (a, b) = (1.2, 2.6)
is (1.2, 2)
, while (2, 3)
overlaps at (2, 2.6)
. (1, 2)
has a larger overlapping range ((1.2, 2)
vs (2, 2.6)
), so in this case we choose (1, 2)
.
Sometimes there are two options with the same overlapping length. For example, (0.5, 1.5) -> (0, 1), (1, 2)
. In such cases, either could be, but one should be, chosen.
Examples
0 ≤ a < b
b - a ≥ 1
(a, b) -> (ra, rb)
(1, 2) -> (1, 2)
(1, 3.9) -> (1, 3)
(1.1, 4) -> (2, 4)
(1.2, 4.6) -> (1, 4)
(1.3, 4.7) -> (1, 4) or (2, 5)
(1.4, 4.8) -> (2, 5)
(0.5, 10.5) -> (0, 10) or (1, 11)