How to calculate aspect ratio from floating point number

I am assigned a floating number, such as 1.77720212936401, and I want to be able to calculate roughly the aspect ratio as the width: the height of the line with the width and height being small natural numbers.

Jd

///

I came up with this, currently checking to see if it covers all areas:

    static public string Ratio(float f)
    {
        bool carryon = true;
        int index = 0;
        double roundedUpValue = 0;
        while (carryon)
        {
            index++;
            float upper = index*f;

            roundedUpValue = Math.Ceiling(upper);

            if (roundedUpValue - upper <= (double) 0.1)
            {
                carryon = false;
            }
        }

        return roundedUpValue + ":" + index;
    }
+3
source share
4 answers

Try multiplying it by small integers in a loop and see if the result is close to an integer.

double ar = 1.7777773452;
for (int n = 1; n < 20; ++n) {
    int m = (int)(ar * n + 0.5); // Mathematical rounding
    if (fabs(ar - (double)m/n) < 0.01) { /* The ratio is m:n */ }
}
+3
source

Check wikipedia , use predefined values ​​and evaluate the closest ratio.

+1
source

, 1.777: 1, , .

0

In most cases, the actual input is not a floating point number, but you have a width , a height , and you get a floating point number dividing them.

In this case, the problem can be reduced to detecting the greatest common factor :

private static int greatestCommonDivisor(int a, int b) {
    return (b == 0) ? a : greatestCommonDivisor(b, a % b);
}

private static String aspectRatio(int width, int height) {
    int gcd = greatestCommonDivisor(width, height);

    if (width > height) {
        return String.Format("{0} / {1}", width / gcd, height / gcd);
    } else {
        return String.Format("{0} / {1}", height / gcd, width / gcd);
    }
}
0
source

Source: https://habr.com/ru/post/1733028/


All Articles