Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the aspect ration from a floating point number

Tags:

c#

I am given a floating number such as 1.77720212936401 and I want to be able to calculate roughly what the aspect ratio is as a width:height string with width and height being small natural numbers.

JD

///

I have come up with this, currently testing 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;
    }
like image 458
JD. Avatar asked Oct 26 '25 06:10

JD.


1 Answers

Try multiplying it by small integers in a loop and check 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 */ }
}
like image 179
Tronic Avatar answered Oct 27 '25 21:10

Tronic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!