We touched on how numbers work in Python a while back in the beginning of our series on Python. In the past few tutorials we discussed strings and how to manipulate them and some of the string methods. Here, in this article, we will go over some of the math modules and discuss different uses for numbers in Python.
Python converts your integer into a long if need be automatically, so you don't really need to concern yourself with this issue. However, there is an issue you should be concerned about, and that is in regards to division. Try typing the following in the command prompt of your Python Shell:
>>> 14/6
As you can see, your result is 2. However, if you multiply 6 * 2, you will get 12. So clearly the division isn't right. Unless you are in third grade, or are a complete moron, you know that this is because there was a remainder, and the number has been rounded down. This occurs when you divide two integers. If you want to get the true value, there are several methods you can use, each of which is shown below:
>>> 14/6.0
2.3333333333333335
The above example is probably the simplest. All you do is change one of the numbers into a decimal and it will give you the full result. Don't worry about the long line of numbers following the decimal; we'll learn to shorten that later.
Another way to fix the problem is with the decimal module, like so:
>>> from decimal import Decimal
>>> Decimal(14)/Decimal(6)
Decimal("2.333333333333333333333333333")
The decimal module is a built-in module that gives more accurate results than your typical binary floating point math, particularly when you use it for certain types of calculations, such as calculating percentages, equality testing, and my buddy the modulo calculation.
The line above, from decimal import Decimal, is how we call the decimal module.
One final method to fix this problem is using the mighty Guido Van Rossum's __future__ module. Please note, (I have yet to see anyone explain this, and save a writer a day of banging his head on the desk) that the __future__ module is comprised of two _ on each side, not one, as in _future_. Here is how the __future__ module works. Can I say that one more time? You bet I can...__future__ module:
>>> from __future__ import division
>>> 13/3
4.333333333333333
Be careful not to use the __future__ module too often however; rumor has it that Van Rossum turns into a giant Sasquatch (as opposed to the midget kind) every time it is invoked.