Integer Division in Python
In Python, integer division between two integers results in an integer, even if the result would otherwise be a decimal fraction. This behavior can be surprising to those accustomed to other programming languages.
Example:
Consider the following code:
Here, we would expect the result to be 0.1111111111111111, since the difference between 20 and 10 is 10, and the difference between 100 and 10 is 90. However, Python evaluates each side of the division as an integer, resulting in 0. Since 0 divided by 90 equals 0, the final answer is rounded to 0.
Fix:
To obtain the desired result, you can cast one of the numbers to a float:
Alternatively, you can import the "division" future feature, which changes the behavior of the "/" operator to always return a float:
By understanding the default integer division behavior in Python, you can avoid unexpected results and ensure that your code produces the desired outcomes.
The above is the detailed content of How Does Python Handle Integer Division, and How Can I Get Floating-Point Results?. For more information, please follow other related articles on the PHP Chinese website!