Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum size that matches aspect ratio

Tags:

c#

.net

algorithm

I need to find the minimum size that has an aspect ratio of exactly (or within 0.001) some value. Are there any quick math tricks or framework tricks for doing this?

Here's the pseudo code for the current bad idea I had running in O(n^2):

epsilon = 0.001;

from x = 1 to MAX_X
{
  from y = 1 to MAX_Y
  {
    if(Abs(x / y - aspectRatio) <= epsilon)
    {
      return new Size(x, y);
    }
  }
}
return Size.Empty;
like image 391
TheCloudlessSky Avatar asked Jan 21 '23 14:01

TheCloudlessSky


2 Answers

Unusual. You need to find the greatest common divisor and divide width and height by it. The algorithm is by Euclid and is two thousand three hundred years old. Details are here.

like image 127
Hans Passant Avatar answered Jan 30 '23 04:01

Hans Passant


You can write aspectRatio as a fraction (if you want it up to a presicion of 0.001, than you can use round(aspectRatio,3)/1000 )

Then, simplify this fraction. The resulting fraction is the x/y you're looking for.

like image 38
Ofri Raviv Avatar answered Jan 30 '23 06:01

Ofri Raviv