What formula to calculate the following:

Given:

$width = 300; $height = 500.5; $scale = 16/9; 

I need to pick the integers $newWidth and $newHeight to match the conditions

 $newWidth / $newHeight == $scale && $newWidth >= $width && $newHeight >= $height 

Explain in words or a formula, how to count it?

There is a sketch:

 function aloe($width, $height, $scale){ if ($width / $height > $scale) { $newWidth = $width; $newHeight = round($width / $scale); } else { $newHeight = $height; $newWidth = round($height * $scale); } return $newWidth / $newHeight; } 

But for some reason, the result has an error:

 echo ( aloe(300, 500, 1.55) === aloe(233, 123, 1.55) ? "Все ок" : "Погрешность!"); //Погрешность! 
  • Well, why do not you bring an intermediate result and look? You have round in your calculations, so a mismatch is quite expected. - VladD
  • What is the size error? - D-side
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Still logical.

  1. Your height must be a multiple of 9
  2. And the width is respectively a multiple of 16

Start the cycle, go through the heights starting from 501 , which modulo 9 will give 0 .

Those. Height mod 9 == 0

The nearest integer is 504 , I will tell you.

Therefore the width will be equal to: 504 / 9 * 16 = 896

width 896 16 ------ = --- = -- height 504 9 All conditions are met.

Here is the code. In PHP not strong, but I think it will be clear. Displays True .

 $width = 300; $height = 500.5; $scale = 16 / 9; while (round($height) % 9 != 0) { $height++; } $new_height = round($height); $new_width = $new_height / 9 * 16; echo($new_height); echo($new_width); if (($scale == $new_width / $new_height) && ($new_width >= $width) && ($new_height >= $height)) { echo("True"); } 

If only the relationship is known, it is also easy:

 $scale = 1.55; $width = 1; $height = 1; while ($width / $height != $scale) { $width++; $height = intval($width / 1.55); } echo($width); echo($height); 

Result: 31/20

  • and if not known in advance either 16 or 9? Only the result of dividing 16 by 9 is known, or, for example, 1.55. - Vitalka
  • @Vitalka, well, you can restore the division by reverse multiplication) - Vasily Barbashev
  • @ Vasily Barbashev eeem, multiplying by what? we do not know not divisible, not divisor. Only private. - Vitalka
  • @Vitalka missed the moment that both may not be known) I apologize - Vasily Barbashev
  • @Vitalka Well, what is 1.55, if not 31/20? :) - Harry