Trying to find a reason why `(n * 2) / 4 == (n / 4) * 2` works

47 Views Asked by At

Earlier today I was programming an example in Lua that takes in the diameter of a circle and outputs the area.

circle_darea = function(diameter)
   local radius = diameter / 2
   return self.pi * radius * radius
end;

A first iteration would probably produce the above code. But being me, I wanted to use the diameter directly instead of the local variable. So I came up with the following code.

circle_darea = function(diameter)
   return self.pi * (diameter/2) * (diameter/2)
end;

However, this repeats the diameter twice and I pondered if there was another way, not that this isn't a correct solution. The function explicitly converted the diameter or 'inlined' it. I produced the following code.

circle_darea = function(diameter)
   return self.pi * ((diameter * 2)/4)
end;

This struck me as very odd because it introduces this math rule: (n * 2) / 4 == (n / 4) * 2. Indeed it does seem to be law. So then I did a little research to re-familiarize myself with the basic rules of algebra and the closest I saw was Associative property of multiplication but with a side note of (and division).

One thing I have not tried is replacing the 2's with a unique variable and the 4's with a unique variable to see if it is reoccurring in other forms. Does anyone have an explanation of why this is happening?

1

There are 1 best solutions below

3
On BEST ANSWER

Divide means: multiply by the reciprocal. So $$ \frac{n \cdot 2}{4} = n \cdot 2 \cdot \frac{1}{4} $$ and $$ \frac{n}{4}\cdot 2 = n \cdot \frac{1}{4}\cdot 2 $$ These are equal according to the commutative property of multiplication.