Using Math Modules

Along with the arithmetic operators (covered in Chapter 3) and the basic math functions of the_builtin_module (introduced in Chapter 2) that's always available when you use Python, Python has several modules that provide math functions.

Tip To import any of the math modules, type import followed by the name of the module. Use the following list to guide you to the module you need:

• Real numbers: The math module has most of the functions you need for real numbers. To see all the functions, type this into the interpreter:

• Complex numbers: The cmath module, for complex numbers, has most of the same functions as the math module but returns results as a complex number type (for example, 3+6j—see "Imagining Complex Numbers," earlier in this chapter).

The cmath module also returns values for calculations such as the square root of a negative number. (The math module treats such calculations as errors.)

Warning If you're working with both complex and real numbers, use the module name (such as cmath.sqrt() or math.sqrt() ) when calling a function. Many of the two modules' functions have the same names but work differently. The module name helps you keep track of which function you're using. Decimal numbers: The decimal module lets you work with decimal numbers rather than binary floating point numbers.

Tip Decimal numbers give more accurate results for many calculations. See "Turning Python into a Calculator with decimal," later in this chapter. Random numbers: The random module includes tools for such tasks as generating random numbers and choosing randomly from several elements. For a fun introduction to the tricks up the sleeve of the random module, see Chapter 21.

Was this article helpful?

0 0

Post a comment