# Python: Count on It

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.

Intergalactic Integers Intentionally Invaded Iraq Intent on Infiltrating Its Islamic Oil

Yeah you heard me. Try saying that headline three times fast. Or even slow. Although I am sure there is a way we could do just that with our Python integers, it won’t be the focus of today’s article. Instead we will cover more fascinating subjects, like explaining why our buddy Python has two types of integers. Shocking, I know.

As you know, integers are whole numbers, both positive and negative, that do not have a value to the right of the decimal point. There are two kinds of integers in Python: regular and long.

The reason for the two types of integers is that computers handle data larger than 32 bytes by assigning the suffix L to the end of the integer. Any number less than 2,147,483,647 is considered a regular integer; anything larger is a long integer. To see an example of what I mean, type the following at your command prompt:

>>> num=2147483647

>>> num*1

2147483647

Now to see a long, we are going to add one to our number:

>>> num=2147483648

>>> num*1

2147483648L

{mospagebreak title=Decimals, Division, and Floats}

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.

{mospagebreak title=Floating Points}

As we discussed way back in one of the beginning tutorials on Python, a floating point refers to a decimal value. Floating points in Python have a size limit of 17 decimal digits, the largest being 1.79769_10308. Any number larger will result in an error, or a line that says: inf (standing for infinity).

Let’s take a look at the following float value:

>>> 4.1*9

36.899999999999999

That’s a pretty crazy number of digits to the right of the decimal. What if we don’t want to see those? We can format our floating points using the str() function, which allows us to display the number as a string:

>>> 4.1*9

36.899999999999999

>>> str(4.1*9)

‘36.9’

You can also use the round function to round out the number, like so:

>>> round(4.1*9)

37.0

But what if you have a number such as 52.9 and you want it to return 52.0 instead of 53.0, since technically, it isn’t 53.0. Try using round first:

>>> round(52.9)

53.0

As you can see, round makes it 53.0 automatically. So what do we do if we want it to show 52.0 instead? We use the floor module, that’s what:

>>> import math

>>> math.floor(52.9)

52.0

Voila! Easy as pie. That you buy in a supermarket and don’t actually make yourself.

Of course, if you are in the reverse situation, you can use our pal, the ceil module (short for ceiling) which does the opposite of the floor module:

>>> import math

>>> math.ceil(53.1)

54.0

If you want to control how many decimals are displayed, you can use %f to format it. Let’s say you want to see the number 19 as a decimal. Try typing in the following code:

>>> print "%f" % 19

19.000000

As you can see, it has taken your integer, 19, and formatted it as a decimal, giving the result 19.000000. But what if you only wanted two decimal places? Try this:

>>> print "%.2f" % 19

19.00

If you had typed in %.3f, you would have gotten this result:

>>> print "%.3f" %19

19.000

and so forth, up until %.68f.

{mospagebreak title=Built-in Math Functions}

There are several built-in functions in Python. We will discuss some of them below.

Working those Abs

The abs function returns the absolute value of a number. Try the following examples:

>>> print abs(9000)

9000

>>> print abs(-9000)

9000

>>> print abs(12.6)

12.6

>>> print abs(-12.6)

12.6

Min and Max…Always Comparing

If you need to find the largest or smallest number in a list, you can count on these two fellas to help you do so. Here they both are at work:

>>> print max([100, 200, 2, 4, 900, 6, 8000])

8000

>>> print min(1000, 2000, 2, 1, 19, 80)

1

Summing Up the Range

If you ever find yourself wanting to sum up a range of numbers, you can do so by combining sum and range, like in the following program, where we calculate 1+2+3+4+5+6+7+8+9:

>>> print sum(range(1, 10))

45

In addition to the built-in functions, you can also work with modules, some of which we have already been using, like the math module and the decimal module. Here are some of the uses of the math module:

Square Root

>>> import math

>>> math.sqrt(3)

1.7320508075688772

>>> math. sqrt(9)

3.0

>>> math.sqrt(32)

5.6568542494923806

>>> math.sqrt(1200)

34.641016151377549

>>>

Remember when using a module to import it first.

Exponentiation

>>> math.exp(12)

162754.79141900392

>>> math.exp(1)

2.7182818284590451

>>> math.exp(50)

5.184705528587072e+021

Math, unfortunately, ended for me in the ninth grade, so I can’t really tell you what all of these functions do, but here is a list of the ones you will find in the math module:

• sqrt: square root
• exp: exponentiation
• log/log10: natural logarithm/base 10 logarithm
• sin/cos/tan: trigonometric functions
• sinh/cosh/tanh: hyperbolic functions
• asin/acos/atan: inverse trigonometric functions
• hypot: equal to sqrt(x**2+y**2)
• atan2: similar to atan but gets the quadrant right and handles a 0 denominator
• floor/ceil: seen earlier in the article
• pi and e: Something you can eat, or math that I don’t understand.

Other modules include the cmath, which is used for complex numbers and has many of the same functions as math, yet returns results as a complex number type; the decimal module, that works with decimal numbers as opposed to floating points; and the random module, which has functions that allow you to generate random numbers and choose randomly from different elements.

Conclusion

Well that’s it for this article. Now go forth and do brilliant math stuff with Python. I’ll just be slaving away here, hard at work on the next programming tutorial. Check back frequently for another dazzling display from my massive stores of knowledge.

Till then…