Approximate ratio with a small fraction so that numerator multiplied by denominator give enough rectangular area?

330 Views Asked by At

I would like to layout given number of objects (like plots) into rectangular area (like computer operating system window on screen).

I would like to calculate the width and height of the window (in columns and rows of objects) for given number of objects.

I thought, that having number of objects $N$, it would be possible to take overall screen ratio $R$, like $R=4:3$ or $R=16:9$ and approximate $N$ with small fraction $\frac{A}{B} \approx R$ so that rectangle with width of a cells and height of $B$ cells is minimally enough to fit all $N$ objects, i.e. $A B \geq N$ while both $A (B-1) < N$ and $(A-1) B < N$

enter image description here

Any hint for this task would be appreciated.

Also I am interested, is it related somehow with my another question: How to divide natural number N into M nearly equal summands?

UDPATE

Currently I do this with the following Python script (result may not coincide with what I drew):

def getSidesByRatio(numberOfElements, ratio =16.0 / 9):

  if not isinstance(numberOfElements, int):
    raise TypeError('value should be integer')

  bestdistance = 0
  bestwidth = 0
  bestheight = 0
  for width in range(1, numberOfElements+1):
    height = int(math.ceil(numberOfElements * 1.0 / width))
    myratio = width * 1.0 / height
    mydistance = abs(myratio - ratio)
    if width == 1 or bestdistance > mydistance:
      bestdistance = mydistance
      bestwidth = width
      bestheight = height
  return [bestheight, bestwidth]