There are a number of modules in the Python standard library that add-on to the functionality of the operators and built-in functions for numeric types. Table 5.7 lists the key modules for use with numeric types. Refer to the literature or online documentation for more information on these modules.
For advanced numerical and scientific mathematics applications, there is also a well known external module called NumPy which may be of interest to you.
CORE MODULE: random
The random module is the general-purpose place to go if you are looking for random numbers. The random number generator (RNG), based on the Wichmann-Hill algorithm, comes seeded with the current timestamp and is ready to go as soon as it has loaded. Here are four of the most commonly used functions in the random module:
randint() | takes two integer values and returns a random integer between those values inclusive |
uniform() | does almost the same thing as randint(), but returns a float and is inclusive only of the smaller number (exclusive of the larger number) |
random() | works just like uniform() except that the smaller number is fixed at 0.0, and the larger number is fixed at 1.0 |
choice() | given a sequence (see Chapter 6), randomly selects and returns a sequence item |
We have now come to the conclusion of our tour of all of Python's numeric types. A summary of operators and built-in functions for numeric types is given in Table 5.8.
Operator/built-in | Description | int | long | float | complex | Result [a] |
---|---|---|---|---|---|---|
abs() | absolute value | • | • | • | • | number[a] |
chr() | character | • | • | string | ||
coerce() | numeric coercion | • | • | • | • | tuple |
complex() | complex conversion | • | • | • | • | complex |
divmod() | division/modulo | • | • | • | • | tuple |
float() | float conversion | • | • | • | • | float |
hex() | hexadecimal string | • | • | string | ||
int() | int conversion | • | • | • | • | int |
long() | long conversion | • | • | • | • | long |
oct() | octal string | • | • | string | ||
ord() | ordinal | (string) | int | |||
pow() | exponentiation | • | • | • | • | number |
round() | float rounding | • | float | |||
** [b] | exponentiation | • | • | • | • | number |
+ [c] | no change | • | • | • | • | number |
- [c] | negation | • | • | • | • | number |
~ [c] | bit inversion | • | • | int/long | ||
** [b] | exponentiation | • | • | • | • | number |
* | multiplication | • | • | • | • | number |
/ | division | • | • | • | • | number |
% | modulo/remainder | • | • | • | • | number |
+ | addition | • | • | • | • | number |
- | subtraction | • | • | • | • | number |
<< | bit left shift | • | • | int/long | ||
>> | bit right shift | • | • | int/long | ||
& | bitwise AND | • | • | int/long | ||
^ | bitwise XOR | • | • | int/long | ||
| | bitwise OR | • | • | int/long |
[a] a result of “number” indicates any of the four numeric types
[b] has a unique relationship with unary operators; see Section 5.5.3 and Table 5.2
[c] unary operator