# How would you write the aspect ratio when height is greater than width?

If you have an image that is sized 200x100 you would say the aspect ratio is "2:1" correct? You can figure that out with width/height correct? What if the size was 100x200? Would you say the aspect ratio is "1:2"? If so how do you do the math to get "1:2" instead of ".5:1".

I have to figure this out in code and format it correctly. Here is as far as I got. Does the following look right?

width = 200
height = 100

if (width > height) {
ratio = width/height + ":1" // results in "2:1"
}
else if (height > width) {
ratio = "1:" + height/width // results in "1:2"
}
else if (width == height) {
ratio = "1:1";
}


I'm not even sure I described what I'm trying to do correctly. Sorry!

-
Conventionally, width comes first. And anyone familiar with photography will have no problem understanding. But if you are communicating with non-photographers, it is best to be explicit. –  André Nicolas Nov 28 '12 at 3:26

A ratio is essentially a fraction. When you say the ratio of the width to the height is $2:1$, you mean: $$\frac{width}{height}=\frac{2}{1}$$

If the ratio if $1:2$, this means: $$\frac{width}{height}=\frac{1}{2}$$

Thus, your problem is equivalent to reducing a fraction.

Example: The height is 200, the width is 300. Thus: $$\frac{width}{height}=\frac{300}{200}=\frac{3}{2}$$ Written as a ratio, this is $3:2$.

How do you reduce a fraction? Compute the greatest common divisor (GCD) of the numerator and denominator. Then divide the numerator and denominator by the the GCD. Information on computing the GCD can be found on Wikipedia: http://en.wikipedia.org/wiki/Greatest_common_divisor. Look at Euclid's Algorithm.

What would this look like in pseudocode? Assuming you have written a function to find the GCD of two numbers called gcd():

w = some input //this is the width variable
h = some input //this is the height variable

divisor = gcd(w, h)

w = w / divisor
h = h / divisor

print (w:h)

-
Thank you anorton! Great answer! –  1.21 gigawatts Nov 28 '12 at 3:37