Next / Previous / Contents / TCC Help System / NM Tech homepage

2.3. More mathematical operations

Python has a number of built-in functions. To call a function in Python, use this general form:

f(arg1, arg2, ... )

That is, use the function name, followed by an open parenthesis “(”, followed by zero or more arguments separated by commas, followed by a closing parenthesis “)”.

For example, the round function takes one numeric argument, and returns the nearest whole number (as a float number). Examples:

>>> round ( 4.1 )
4.0
>>> round(4.9)
5.0
>>> round(4.5)
5.0

The result of that last case is somewhat arbitrary, since 4.5 is equidistant from 4.0 and 5.0. However, as in most other modern programming languages, the value chosen is the one further from zero. More examples:

>>> round (-4.1)
-4.0
>>> round (-4.9)
-5.0
>>> round (-4.5)
-5.0

For historical reasons, trigonometric and transcendental functions are not built-in to Python. If you want to do calculations of those kinds, you will need to tell Python that you want to use the math package. Type this line:

>>> from math import *

Once you have done this, you will be able to use a number of mathematical functions. For example, sqrt(x) computes the square root of x:

>>> sqrt(4.0)
2.0
>>> sqrt(81)
9.0
>>> sqrt(100000)
316.22776601683796

Importing the math module also adds two predefined variables, pi (as in π) and e, the base of natural logarithms:

>>> print pi, e
3.14159265359 2.71828182846

Here's an example of a function that takes more than argument. The function atan2(dx , dy) returns the arctangent of a line whose slope is dy/dx.

>>> atan2 ( 1.0, 0.0 )
1.5707963267948966
>>> atan2(0.0, 1.0)
0.0
>>> atan2(1.0, 1.0)
0.78539816339744828
>>> print pi/4
0.785398163397

For a complete list of all the facilities in the math module, see the Python 2.2 quick reference. Here are some more examples; log is the natural logarithm, and log10 is the common logarithm:

>>> log(e)
1.0
>>> log10(e)
0.43429448190325182
>>> exp ( 1.0 )
2.7182818284590451
>>> sin ( pi / 2 )
1.0
>>> cos(pi/2)
6.1230317691118863e-17

Mathematically, cos(π/2) should be zero. However, like pretty much all other modern programming languages, transcendental functions like this use approximations. 6.12×10-17 is, after all, pretty close to zero.

Two math functions that you may find useful in certain situations:

>>> floor(4.9)
4.0
>>> floor(4.1)
4.0
>>> floor(-4.1)
-5.0
>>> floor(-4.9)
-5.0
>>> ceil(4.9)
5.0
>>> ceil(4.1)
5.0
>>> ceil(-4.1)
-4.0
>>> ceil(-4.9)
-4.0

Note that the floor function always moves toward -∞ (minus infinity), and ceil always moves toward +∞.