Linux/Unix > Python Essential Reference, Second Edition > A. The Python Library > Mathematics | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105083198025091079203031

### Mathematics

The modules in this section provide a variety of mathematical functions.

#### `array`

The `array` module defines a new object type `ArrayType` that works almost exactly like other sequence types except that its contents are constrained to a single type. The type of an array is determined at the time of creation, using one of the following typecodes:

Type Code | Description | C Type | Minimum Size (in bytes)
--- | --- | --- | ---
`'c'` | 8-bit character | `char` | 1
`'b'` | 8-bit integer | `signedchar` | 1
`'B'` | 8-bit unsigned integer | `unsignedchar` | 1
`'h'` | 16-bit integer | `short` | 2
`'H'` | 16-bit unsigned integer | `unsignedshort` | 2
`'i'` | integer | `int` | 4 or 8
`'I'` | unsigned integer | `unsigned int` | 4 or 8
`'l'` | long integer | `long` | 4 or 8
`'L'` | unsigned long integer | `unsigned long` | 4 or 8
`'f'` | single-precision float | `float` | 4
`'d'` | double-precision float | `double` | 8

The representation of integers and long integers is determined by the machine architecture (they may be 32 or 64 bits).When values stored as `'L'` or `'I'` are returned, they’re returned as Python long integers.

The module defines the following function:

    array(typecode [, initializer])

Creates an array of type `typecode` . `initializer` is a string or list of values used to initialize values in the array. The following attributes and methods apply to an array object `a` :

Item | Description
--- | ---
`a` `.typecode` | Typecode character used to create the array.
`a` `.itemsize` | Size of items stored in the array (in bytes).
`a` `.append(``x` `)` | Appends `x` to the end of the array.
`a` `.buffer_info()` | Returns `(``address` `,` `length` `)`, giving the memory location and length of the buffer used to store the array.
`a` `.byteswap()` | Swaps the byte ordering of all items in the array from big-endian to little-endian or vice versa. This is only supported for integer values.
`a` `.count(``x` `)` | Returns the number of occurrences of `x` in `a` .
`a` `.extend(``b` `)` | Appends array `b` to the end of array `a` .
`a` `.fromfile(``f` `,` `n` `)` | Reads `n` items (in binary format) from the file object `f` and appends to the end of the array. `f` must be a file object. Raises `EOFError` if fewer than `n` items can be read.
`a` `.fromlist(``list` `)` | Appends items from `list` to the end of the array.
`a` `.fromstring(``s` `)` | Appends items from string `s` where `s` is interpreted as a string of binary values—same as would have been read using `fromfile()`.
`a` `.index(``x` `)` | Returns the index of the first occurrence of `x` in `a` . Raises `ValueError` if not found.
`a` `.insert(``i` `,` `x` `)` | Inserts `x` before position `i` .
`a` `.pop([``i` `])` | Removes item `i` from the array and returns it. If `i` is omitted, the last element is removed.
`a` `.remove(``x` `)` | Remove the first occurrence of `x` from the array. Raises `ValueError` if not found.
`a` `.reverse()` | Reverses the order of the array.
`a` `.tofile(``f` `)` | Writes all items to file `f` . Data is saved in native binary format.
`a` `.tolist()` | Converts the array to an ordinary list of values.
`a` `.tostring()` | Converts to a string of binary data—the same data as would be written using `tofile()`.

When items are inserted into an array, a `TypeError` exception is generated if the type of the item doesn’t match the type used to create the array.

##### Notes

- This module is used to create large lists in a storage-efficient manner. The resulting arrays are not suitable for numeric work. For example, the addition operator doesn’t add the corresponding elements of the arrays; it appends one array to the other. To create storage- and calculation-efficient arrays, use the `Numeric` extension available at http://numpy.sourceforge.net/. Note that the `Numeric` API is completely different.

- The type of an array object is `array.ArrayType`.

? See Also struct (144), xdrlib (277) .

#### `cmath`

The `cmath` module provides mathematical functions for complex numbers. All functions accept and return complex numbers.

Function | Description
--- | ---
`acos(``x` `)` | Returns the arccosine of `x`
`acosh(``x` `)` | Returns the arc hyperbolic cosine of `x`
`asin(``x` `)` | Returns the arcsine of `x`
`asinh(``x` `)` | Returns the arc hyperbolic sine of `x`
`atan(``x` `)` | Returns the arctangent of `x`
`atanh(``x` `)` | Returns the arc hyperbolic tangent of `x`
`cos(``x` `)` | Returns the cosine of `x`
`cosh(``x` `)` | Returns the hyperbolic cosine of `x`
`exp(``x` `)` | Returns `e **` `x`
`log(``x` `)` | Returns the natural logarithm of `x`
`log10(``x` `)` | Returns the base 10 logarithm of `x`
`sin(``x` `)` | Returns the sine of `x`
`sinh(``x` `)` | Returns the hyperbolic sine of `x`
`sqrt(``x` `)` | Returns the square root of `x`
`tan(``x` `)` | Returns the tangent of `x`
`tanh(``x` `)` | Returns the hyperbolic tangent of `x`

The following constants are defined:

Constant | Description
--- | ---
`pi` | Mathematical constant pi, as a real
`e` | Mathematical constant e, as a real

? See Also math (129).

#### `math`

The `math` module defines standard mathematical functions. These functions operate on integers and floats, but don’t work with complex numbers.

Function | Description
--- | ---
`acos(``x` `)` | Returns the arccosine of `x`
`asin(``x` `)` | Returns the arcsine of `x`
`atan(``x` `)` | Returns the arctangent of `x`
`atan2(``y` `,` `x` `)` | Returns atan(`y` `/` `x` )
`ceil(``x` `)` | Returns the ceiling of `x`
`cos(``x` `)` | Returns the cosine of `x`
`cosh(``x` `)` | Returns the hyperbolic cosine of `x`
`exp(``x` `)` | Returns `e **` `x`
`fabs(``x` `)` | Returns the absolute value of `x`
`floor(``x` `)` | Returns the floor of `x`
`fmod(``x` `,` `y` `)` | Returns `x` `%` `y`
`frexp(``x` `)` | Returns the positive mantissa and exponent of `x`
`hypot(``x` `,` `y` `)` | Returns the Euclidean distance, `sqrt(``x` `*` `x` `+` `y` `*` `y` `)`
`ldexp(``x` `,` `i` `)` | Returns `x` `* (2 **` `i` `)`
`log(``x` `)` | Returns the natural logarithm of `x`
`log10(``x` `)` | Returns the base 10 logarithm of `x`
`modf(``x` `)` | Returns the fractional and integer parts of `x` (both have the same sign as `x` )
`pow(``x` `,` `y` `)` | Returns `x` `**` `y`
`sin(``x` `)` | Returns the sine of `x`
`sinh(``x` `)` | Returns the hyperbolic sine of `x`
`sqrt(``x` `)` | Returns the square root of `x`
`tan(``x` `)` | Returns the tangent of `x`
`tanh(``x` `)` | Returns the hyperbolic tangent of `x`

The following constants are defined:

Constant | Description
--- | ---
`pi` | Mathematical constant pi
`e` | Mathematical constant e

? See Also cmath (129).

#### `random`

The `random` module provides a variety of functions for generating pseudo-random numbers as well as functions for randomly generating values according to various distributions on the real numbers. Most of the functions in this module depend on the function `random()`, which generates uniformly distributed numbers in the range (`0.0, 1.0`) using the standard Wichmann-Hill generator.

The following functions are used to control the state of the underlying random-number generator:

    seed([ x ])

Initializes the random-number generator. If `x` is omitted or is `None`, the system time is used to seed the generator. Otherwise, if `x` is an integer or long integer, its value is used. If `x` is not an integer, it must be a hashable object and the value of `hash(``x` `)` is used as a seed.

    getstate()

Returns an object representing the current state of the generator. This object can later be passed to `setstate()` to restore the state.

    setstate(state)

Restores the state of the random-number generator from an object returned by `getstate()`.

    jumpahead(n)

Quickly changes the state of the generator to what it would be if `random()` were called `n` times in a row. `n` must be a non-negative integer.

The following function can be used to generate random integers:

    randrange(start, stop [, step])

Returns a random integer in `range(``start` `,``stop` `,``step` `)`. Doesn’t include the endpoint.

The following functions can be used to randomly manipulate sequences:

    choice(seq)

Returns a random element from the nonempty sequence `seq` .

    shuffle(x [, random])

Randomly shuffles the items in the list `x` in place. `random` is an optional argument that specifies a random-generation function. If supplied, it must be a function that takes no arguments and that returns a floating-point number in the range (`0.0, 1.0`).

The following functions generate random numbers on real numbers. Parameter names correspond to the names in the distribution’s standard mathematical equation.

    betavariate(alpha, beta)

Returns a value between `0` and `1` from the Beta distribution. `alpha` `> -1` and `beta` `> -1`.

    cunifvariate(mean, arc)

Circular uniform distribution. `mean` is the mean angle and `arc` is the range of the distribution, centered around the mean angle. Both of these values must be specified in radians in the range between `0` and `pi`. Returned values are in the range `(``mean` `-` `arc` `/2,` `mean` `+` `arc` `/2)`.

    expovariate(lambd)

Exponential distribution. `lambd` is `1.0` divided by the desired mean. Returns values in the range `(0, +8)`.

    gamma(alpha, beta)

Gamma distribution. `alpha` `> -1,` `beta` `> 0`.

    gauss(mu, sigma)

Gaussian distribution with mean `mu` and standard deviation `sigma` . Slightly faster than `normalvariate()`.

    lognormvariate(mu, sigma)

Log normal distribution. Taking the natural logarithm of this distribution results in a normal distribution with mean `mu` , standard deviation `sigma` .

    normalvariate(mu, sigma)

Normal distribution with mean `mu` and standard deviation `sigma` .

    paretovariate(alpha)

Pareto distribution with shape parameter `alpha` .

    vonmisesvariate(mu, kappa)

von Mises distribution where `mu` is the mean angle in radians between `0` and `2 * pi`, and `kappa` is a non-negative concentration factor. If `kappa` is zero, the distribution reduces to a uniform random angle over the range `0` to `2 * pi`.

    weibullvariate(alpha, beta)

Weibull distribution with scale parameter `alpha` and shape parameter `beta` .

##### Notes

- The `Numeric` extension also provides a number of efficient generators for large samples and creating independent random-number streams.

- The functions in this module are not thread-safe. If you’re generating random numbers in different threads, you should use locking to prevent concurrent access.

- The period of the random-number generator (before numbers start repeating) is 6,953,607,871,644. Although this is better than that found in many programming libraries, it’s not suitable for all applications—especially those related to cryptography.

- New types of random-number generators can be created by subclassing `random.Random` and implementing the `random()`, `seed()`, `getstate()`, `getstate()`, and `jumpahead()` methods. All the other functions in this module are actually internally implemented as methods of `Random`. Thus, they could be accessed as methods on an instance of the new random-number generator.

- Significant modifications were made to this module in Python 2.1. Furthermore, some of its functionality was previously found in the deprecated `whrandom` module. Please refer to the online documentation for details of these changes.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.