Why the Division Rounds to an Integer
In Python, division between integers results in an integer. This behavior can be surprising, especially when trying to normalize or adjust numerical ranges.
To illustrate this, let's consider the following code:
One might expect this expression to evaluate as a float value representing 0.111, since the difference between 20 and 10 is 10 and the difference between 100 and 10 is 90. However, the result is 0 because both sides of the division are integers.
This behavior is due to Python's integer division, which truncates the result rather than rounding it. Since 0.111 is less than 0.5, it rounds down to 0.
To obtain the expected result, one must manually convert either side of the division to a float:
Alternatively, one can enable Python 3.x's behavior, which forces division to return a float, by importing the future module:
The above is the detailed content of Why Does Integer Division in Python Truncate Instead of Rounding?. For more information, please follow other related articles on the PHP Chinese website!