✐

✐

“91974˙CH02˙ﬁnal” — 2012/12/14 — 13:58 — page 47 — #3

✐

✐

✐

✐

✐

✐

2.3 More About the math Module 47

Session 2.1 shows the interactive Python environment as we evaluate each of these approx-

imations.

>>> 22/7

3.1428571428571428

>>> 355/113

3.1415929203539825

>>> import math

>>> 9801/(2206*math.sqrt(2))

3.1415927300133055

>>>

Session 2.1 Simple approximations for pi

There is one Python element that is new in Session 2.1: the statement import math. Recall

that the import statement allows us to gain access to a Python module that contains

additional functionality that we might ﬁnd useful. In this case, we need to compute the

square root of 2. After loading the math module, we can use the sqrt() function to do

this for us.

2.3 More About the

math

Module

As we mentioned earlier, there are many mathematical helper functions available in the

math module. Unfortunately, it is sometimes diﬃcult to know what they are and what

they are called. To remedy this, Python has a built-in help subsystem that allows you to

see the documentation for a particular module. To use help, simply give the command

help("modulename") where the module name is the particular module you are interested

in. For example, Session 2.2 shows the result of asking for help on the math module. You

might ﬁnd it interesting that in addition to typical math functions such as sin, log, and

pow, the math module contains two constants, e and pi.

✐

✐

“91974˙CH02˙ﬁnal” — 2012/12/14 — 13:58 — page 48 — #4

✐

✐

✐

✐

✐

✐

48 CHAPTER 2

π

thon

>>> help("math")

Help on module math:

NAME

math

FILE

.../lib-dynload/math.so

MODULE DOCS

http://www.python.org/doc/current/lib/module-math.html

DESCRIPTION

This module is always available. It provides access to the

mathematical functions defined by the C standard.

FUNCTIONS

acos(...)

acos(x)

Return the arc cosine (measured in radians) of x.

asin(...)

asin(x)

Return the arc sine (measured in radians) of x.

.

.many more functions here...

.

sqrt(...)

sqrt(x)

Return the square root of x.

tan(...)

tan(x)

Return the tangent of x (measured in radians).

tanh(...)

tanh(x)

Return the hyperbolic tangent of x.

DATA

e = 2.7182818284590451

pi = 3.1415926535897931

>>>

Session 2.2 Asking for help on a Python module

Start Free Trial

No credit card required