tags:

views:

90

answers:

3

afternoon all. Iv'e come across some mathematical problems that im not too good at. does anyone know how to calculate the ratio for Height against width?

Regards Phil

+2  A: 

Pseudo code:

newWidth = newHeight / oldHeight * oldWidth

OR

newHeight = newWidth / oldwidth * oldHeight
thephpdeveloper
A: 

If you mean the aspect ratio of a height and width, it's just height / width reduced to its greatest common factor.

For instance, if your monitor is 1600 x 1200, it's 1600/1200 reduced to 4/3. To do this:

In math terms, you have to find the "Greatest Common Factor" and divide both values (1600 and 1200) by that. In this case, it's 400.

A very simple (and relatively) algorithm for this is:

for i <= min( 1600, 1200 ); i > 0; --i );
  if( 1600 % i == 0 && 1200 % i == 0 ) {
    minTop = 1600 / i;
    minBottom = 1200 / i;
    break;
  }
}

Your answer is minTop / minBottom. Replace 1600 and 1200 with the width and height you want, respectively.

Basically, the algorithm goes like this: count down from the lesser of the two numbers and find the first number into which both 1600 and 1200 divide into evenly (using the mod operator, so remainder == 0). That will end up being 400. That leads you with (1600 / 400) / (1200 / 400), or 4/3.

Hope this helps; leave a comment with any questions and I'll try to help further.

Outdoor83
what ? how do you go programmatically from 1333/1000 to 4/3 ??
Gyom
Easiest way to do that is to multiply both by 1000, round off, and then Multiply or divide?
Phil Jackson
This one is more on the lines of what i am after but not quite getting you...
Phil Jackson
+2  A: 

Here is a simple function that should give you the aspect ratio (simplified and in javascript)

function getAspectRatio(w, h)
    {
        var rem;
        var newW = w;
        var newH = h;

        while (h != 0)
        {
            rem = w % h;
            w = h;
            h = rem;
        }

        newH = newH / w;
        newW = newW / w;

        alert("Aspect Ratio: " + newW + ":" + newH);
    }

getAspectRatio(800,600); results in 4:3.

Hope this helps

G

EDIT: I forgot to mention, it calculates the gcd of the two numbers and does not check for division by zero, so you might want to add that. :)

gg
keeps returning NaN:NaNfunction calcRatio(){ $(".heightAndWidth").keypress(function (e) { var rem; var newW = 20; var newH = 100; while (h != 0){ rem = w % h; w = h; h = rem; } newH = newH / w; newW = newW / w; alert("Aspect Ration : " + newW + ":" + newH); }); }
Phil Jackson
sussed many thanks
Phil Jackson