[Tutor] Division operation
Terry Carroll
carroll at tjc.com
Tue May 16 22:17:52 CEST 2006
On Tue, 16 May 2006, Miguel Estrada wrote:
> def function():
> x = int(raw_input("Enter value of x: "))
> y = int(raw_input("Enter value of y: "))
> z = x / y
> print "The value of z is", z, "unit of measurement"
>
>
> Now, say, user input:
>
> x = 200
> y = 1000
>
> The value returned will be '0'.
>
> My question: What is the proper way of writing the operation so that if
> z = x /y, the result would be '0.20' instead of just '0'?
This is a frustrating design choice in Python, which I believe is on the
list of Guido's regrets and will be corrected in Python 3.0.
Where both operands are integers, Python division truncates to and integer
result, thus:
>>> x = 200
>>> y = 1000
>>> z = x/y
>>> z
0
But if either operand is a float, you get the results that you'd expect:
>>> x = 200.0
>>> y = 1000
>>> z = x/y
>>> z
0.20000000000000001
>>>
(the "000000..1" is rounding error from the basic impossibility of
representing 1/5 in a binary system)
You can include the following in your program (I often do) if you want
division to operate the way you expect:
>>> from __future__ import division
>>> from __future__ import division
>>> x = 200
>>> y = 1000
>>> z = x/y
>>> z
0.20000000000000001
>>>
More information about the Tutor
mailing list