Can you help me to figure out this Python division
base = 12.0
height = 16
Area = 1/2 * Base * Height
Solution shows of it this
ar
Python2.7 automatically uses the / operator as integer (whole number) division, which will always produce a whole number.
For example:
1/2 = 0
3/4 = 0
100/30 = 3
To do float division, you must have one or both of the values as a float type.
Like this:
Area = 1.0/2 * Base * Height # 1.0 is a float type, 1 is an integer type
The results are not what you expected since Python evaluates the expressions using integer division and order of operations.
If you evaluate 16 * 12 / 2 in Python, Python interprets this as (16 * 12) / 2, or 192 / 2 = 96
If you evaluate 1/2 * 16 * 12, Python interprets this as (((1/2) * 16) * 12) = (0 * 16) * 12
Further examples:
Area = Base * Height * (1.0/2.0)
Python evaluates (1.0/2.0) first this time, since order of operations dictates that the parentheses are evaluated first. And since 1.0 and 2.0 are floats and not integers, Python is fine with performing float division. You get this:
Base * Height * (0.5)
= 192 * 0.5
= 96
, which gives you what you expect.
In contrast:
Base * Height * (1/2)
= Base * Height * (0) # since 1/2 rounds down to 0 in integer division
= 192 * 0
= 0
Alternative solution from Carpetsmoker:
from __future__ import division
This line will give you Python3.x behaviour in a Python2.x program, and Python3.x accepts the / operator as float division, even if both values are integer types. Thus, after you import this, / becomes the float division operator.
>>> from __future__ import division
>>> 1/2
0.5