Minimum Aspect Ratio

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

Here's the pseudo code for the current bad idea I was working with 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; 
+4
source share
5 answers

Unusual. You need to find the largest common divisor and divide its width and height. The algorithm is Euclid and is two thousand three hundred years old. More details here .

+6
source

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

Then simplify this share . The resulting fraction is the x / y you are looking for.

+1
source

A faster way, but still not stereotyped, would be to look only at the possible values โ€‹โ€‹of y, and not at the iteration up to MAX_Y. eg:.

  static Size FindMinSize(double requiredRatio, double epsilon) { int x = 1; do { int y = (int)(x * requiredRatio); if (Test(x, y, requiredRatio, epsilon)) { return new Size(x, y); } y = (int)((x + 1) * requiredRatio); if (Test(x, y, requiredRatio, epsilon)) { return new Size(x, y); } x++; } while (x != int.MaxValue); return new Size(0, 0); } static bool Test(int x, int y, double requiredRatio, double epsilon) { double aspectRatio = ((double)y)/x; return Math.Abs(aspectRatio - requiredRatio) < epsilon; } 
+1
source

Instead of checking all the possible combinations, simply increase the side that brings you closer to the aspect ratio:

 public static Size GetSizeFromAspectRatio(double aspectRatio) { double epsilon = 0.001; int x = 1; int y = 1; while (true) { double a = (double)x / (double)y; if (Math.Abs(aspectRatio - a) < epsilon) break; if (a < aspectRatio) { x++; } else { y++; } } return new Size(x, y); } 
+1
source

Aspect ratio is the ratio between x and y. You can define the aspect ratio as x / y or y / x.

The minimum aspect ratio is 0/0.

It is necessary to determine some other minimum, or minimum x, or minimum y.

min x = (min y * x) / y

min y = (min x * y) / x

0
source

All Articles