Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine bigger number and divide

Ok, I don't know how to put this in short.

This is my code:

var ratio, input={w:100,h:50};
if(input.w <= input.h) ratio = input.h / input.w;
else                   ratio = input.w / input.h;

Question: Is there faster, better, "less code needed" way to calculate ratio ? Than if/else statements.

Thanks!

like image 395
enloz Avatar asked Nov 30 '22 03:11

enloz


2 Answers

You can use the ternary conditional operator. Syntax:

condition ? (statement if true) : (statement if false);

In your case:

ratio = (input.w <= input.h) ? (input.h/input.w) : (input.w/input.h);

EDIT:

This isn't faster than your solution, just faster to write. I would advise against using:

var ratio = Math.Max(input.w, input.h) / Math.Min(input.w, input.h)

That will compare the numbers twice (once in Math.Max, once in Math.Min) and would be slower.

like image 68
Luchian Grigore Avatar answered Dec 09 '22 20:12

Luchian Grigore


var ratio = Math.max(input.w, input.h) / Math.min(input.w, input.h)

another [maybe more efficient]:

var ratio = Math.max(input.w / input.h, 1 / input.w / input.h);

even more efficient than ternary :

var ratio = w / h ;
ratio = ratio > 1 && ratio || 1/ratio
like image 26
Bart Calixto Avatar answered Dec 09 '22 19:12

Bart Calixto