As I refresh my skills in Python 2 to Python 3 semantics I discovered there is a difference in the division operator (i.e. /).
When using integers in Python 2 the result (by default) is an integer. For example.
$ python2 Python 2.7.6 (default, Mar 22 2014, 22:59:56) >>> 1/2 0 >>> 1/2.0 0.5
In Python 3 the result is a float.
$ python3 Python 3.4.0 (default, Apr 11 2014, 13:05:11) >>> 1/2 0.5
It has been encouraged in the Porting Python 2 Code to Python 3 documentation to perform the following import.
$ python2 Python 2.7.6 (default, Mar 22 2014, 22:59:56) >>> from __future__ import division >>> 1/2 0.5
I was also unaware of the floor operator (i.e. //) as specified in PEP 238.
$ python2 Python 2.7.6 (default, Mar 22 2014, 22:59:56) >>> from __future__ import division >>> 1//2 0 >>> 1/2 0.5
I uncovered this by playing with algorithms between versions. This Newton Method for the Square Root was something I was unaware of, and this example failed when using Python 2.
My improved version on the referenced example without an import.
def squareroot(number, precision = 5): root = number/2.0 for i in range(20): nroot = (1/2.0)*(root + (number / root)) #print i, nroot if (root - nroot < 1.0/10**precision): break root = nroot return round(nroot, precision)
>>> squareroot(10) 3.16228 >>> squareroot(10,1) 3.2 >>> squareroot(10,2) 3.16 >>> squareroot(10,5) 3.16228 >>> squareroot(10,10) 3.1622776602