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)
{
开发者_JAVA技巧 index++;
float upper = index*f;
roundedUpValue = Math.Ceiling(upper);
if (roundedUpValue - upper <= (double) 0.1)
{
carryon = false;
}
}
return roundedUpValue + ":" + index;
}
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 */ }
}
Check out wikipedia, use pre-defined values and estimate the nearest ratio.
Perhaps it is 1.777:1 but it is very difficult to be definitive when you tell us so little.
In most cases the actual input is not a floating point number, but you have width, height and you get the floating point number by dividing them.
In such a case, the problem can be reduced to finding the greatest common divisor:
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);
}
}
精彩评论