I've got a (let's say nonnegative) rational number expressed as the ratio of two integers a/b
, where 0 <= a < 2^m
and 0 < b < 2^n
. I'd like to round that to a smaller representation with only p
bits in the denominator; that is, find the largest number c/d
such that c/d <= a/b
, where 0 < d < 2^p
.
Example: if m=3, n=4, p=2
, I'd like to round 4/7
down to 1/2
, and 5/7
down to 2/3
.
My first impulse was to right-shift the denominator by n-p
, adding 1 if a 1 was popped off, and right-shift the numerator by the same amount. That's guaranteed to produce a result less than a/b
, but it doesn't guarantee optimality of the results. For instance, 3/1
rounds to 2/1
.
Ideally, I'd like to do this without division or modulus, but I suspect that might not be practical. m
, n
, and p
may run into the hundreds, and this is going to be in an inner loop, so I'd like something as blazingly fast as possible.