Home >Backend Development >Python Tutorial >How Can I Ensure Floating-Point Division in Python 2 and 3?
Floating Point Division in Python 2
When dividing two integers (ints) in Python 2, the result is an int, even if the division should produce a floating point number. This can be problematic when you need the ratio of two integers as a floating point number.
To force the division to be floating point in Python 2, you can use Python 3's division rules by importing the division module from the future package. Here's how:
from __future__ import division
After importing the division module, division of two ints will produce a float, as shown below:
a = 4 b = 6 c = a / b print(c) # Output: 0.66666666666666663
Note that in Python 3, the division of two ints produces a float by default. To get the old behavior of integer division in Python 3, you can use the // operator, as in the following example:
c = a // b print(c) # Output: 0
The above is the detailed content of How Can I Ensure Floating-Point Division in Python 2 and 3?. For more information, please follow other related articles on the PHP Chinese website!