{ "metadata": { "name": "integer-division" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Integer Division\n", "================\n", "If you're using Python 2.x integer division can be a real gotcha for most scientists. The problem is that in Python 2 if you divide two integers by one another you always get another integer." ] }, { "cell_type": "code", "collapsed": false, "input": [ "9 / 2" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 1, "text": [ "4" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Of course, we all know that 9 / 2 is equal to 4.5, but the folks who write programming languages often want operations involving two objects of the same type to return an object of that type. So, since 9 and 2 are both integers Python 2 returns 4 (i.e., it gets rid of the remainder of the division).\n", "\n", "Fortunately, the good folks who wrote Python have seen the light, and the newest version of Python, Python 3, divides integers as we expect. If you're still using Python 2 (and most scientists still do because a lot of important scientific modules don't work in Python 3 yet) you can make it function in the way you'd expect by using a special command." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from __future__ import division\n", "9 / 2" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 2, "text": [ "4.5" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The idea is that you're asking Python to use the form of division from it's future self. You're importing the function division from the future. The lines on either side of the word future are double underscores, which is Python's way of indicating something special or non-standard.\n", "\n", "If you're worried about getting caught by this strange behaviour (a common issue) you can always add the import line to the beginning of every program just to be safe." ] } ], "metadata": {} } ] }