Let’s say you want fully inclusive wrapping. For simplicity let’s set a to 0.0 and b to 1.0.
Let’s also assume a fixed-point decimal system with one digit below the decimal point: 0.0, 0.1, 0.2 etc. Other numbers don’t exist.
Let’s also consider only positive numbers for now.
So 0.0 wraps to 0.0 (inclusive lower bound), 0.1 to 0.1 … and we want the upper bound to be inclusive, so 1.0 wraps to 1.0 (and therefore cannot wrap to 0.0).
What, then, is the smallest (positive) number that could wrap to 0?
That’s 1.1 → 0, then 1.2 → 1.1, … up to 2.1 → 1.0.
Then 2.2 → 0 and so on.
So 1.0 wraps to 1.0, 2.0 wraps to 0.9, 3.0 wraps to 0.8. Not sure we wanted that.
If we say 2 decimal places, then 1.01 → 0, 2.02 → 0 and so on.
If we let k be the number of places below the decimal point, and c = 10 ^ (-k), then:
- The smallest positive number that can wrap to 0 is 1 + c. (More generally, the smallest number above b that can wrap to a is b+c.)
- That’s also the true wrapping interval – the sequence repeats at intervals of 1+c. (General: the periodicity is b-a+c.)
At higher values of k (more decimal places), the behavior is closer to the b-a range but still inexact: 1+c could be 1.0000000000000001.
So then consider infinite precision: k approaches infinity. Then c approaches 0. At this point, 2.0 would wrap to 0, and 3.0 would wrap to 0 – nice clean intuitive behavior there – but 1.0 also wraps to 0 (because the “smallest number above b that wraps to a” is b+c, but c has approached 0, so b itself must wrap to a). This makes the upper bound exclusive, no longer inclusive.
So you can’t have both. If you want both bounds to be inclusive, you have to choose some value > b to be the “smallest value > a to wrap back to a” and accept that the periodicity will deviate from b-a: the further away from a and b you go, the more the result will be skewed. (At high precision, or if you’re not wrapping from far away, this might be acceptable.) If you can’t accept a compromise on periodicity, then one or the other bound must be exclusive.
You’ve handled only one special case. What happens between 20.0 and 22.0? I bet you’ll see an exclusive bound here.
hjh