0

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.

Sneftel
  • 40,271
  • 12
  • 71
  • 104
  • Python's [`fractions.Fraction.limit_denominator`](https://hg.python.org/cpython/file/2.7/Lib/fractions.py#l206) has some useful notes about this in the source code. You could probably adapt that to whatever language you're working in. – user2357112 Dec 15 '15 at 19:39
  • @user2357112 Not bad! I'm not wild about the division within the loop, but I'll do some analysis to figure out the computational complexity... it might not be too bad. Thanks! – Sneftel Dec 15 '15 at 19:44

0 Answers0