In the first case, 5 ** 2
is computed first as the exact integer 25, which is then multiplied by 3.1416 to get a floating-point approximation of the exact product.
In the second case, 3.1416 * 5
is computed first to get a floating-point approximation, which is then multiplied by 5
again to get a second approximation. Due to the nature of float
, the two values are not guaranteed to be the same.
Put another way, floating-point multiplication is not associative. (x * y) * y
is not guaranteed to be be equal to x * (y * y)
.
(Floating-point multiplication itself is not necessarily repeated addition, as there is no special case to check if one of the operands is an integer, or which one it is. You can add 3.1416 to itself 5 times, but it doesn't make sense to add 5 to itself 3.1416 times.)