You are on page 1of 4

Numeric Types

A complete inventory of Python’s numeric toolbox includes:


• Integers and floating-point numbers
• Complex numbers
• Fixed-precision decimal numbers
• Rational fraction numbers
• Sets
• Booleans
• Unlimited integer precision
• A variety of numeric built-ins and modules

Built-in Numeric Tools


Expression operators
+, -, *, /, >>, **, &, etc.
Built-in mathematical functions
pow, abs, round, int, hex, bin, etc.
Utility modules
random, math, etc.

Here are some examples of complex numbers math at work:


>>> 1j * 1J
(-1+0j)
>>> 2 + 1j * 3
(2+3j)
>>> (2 + 1j) * 3
(6+3j)

>>> oct(64), hex(64), bin(64)


('0100', '0x40', '0b1000000')

The oct function converts decimal to octal, hex to hexadecimal, and bin to binary. To go the other way, the built-in int function converts a string
of digits to an integer, and an optional second argument lets you specify the numeric base:
>>> int('64'), int('100', 8), int('40', 16), int('1000000', 2)
(64, 64, 64, 64)
>>> int('0x40', 16), int('0b1000000', 2) # Literals okay too
(64, 64)

>>> import math


>>> math.pi, math.e # Common constants
(3.1415926535897931, 2.7182818284590451)
>>> math.sin(2 * math.pi / 180) # Sine, tangent, cosine
0.034899496702500969
>>> math.sqrt(144), math.sqrt(2) # Square root
(12.0, 1.4142135623730951)
>>> pow(2, 4), 2 ** 4 # Exponentiation (power)
(16, 16)
>>> abs(-42.0), sum((1, 2, 3, 4)) # Absolute value, summation
(42.0, 10)
>>> min(3, 1, 2, 4), max(3, 1, 2, 4) # Minimum, maximum
(1, 4)

>>> math.floor(2.567), math.floor(-2.567) # Floor (next-lower integer)


(2, −3)
>>> math.trunc(2.567), math.trunc(−2.567) # Truncate (drop decimal digits)
(2, −2)
>>> int(2.567), int(−2.567) # Truncate (integer conversion)
(2, −2)
>>> round(2.567), round(2.467), round(2.567, 2) # Round (Python 3.0 version)
(3, 2, 2.5699999999999998)
>>> '%.1f' % 2.567, '{0:.2f}'.format(2.567) # Round for display (Chapter 7)
('2.6', '2.57')

>>> import math


>>> math.sqrt(144) # Module(when you hear “module,” think “import.”)
12.0
>>> 144 ** .5 # Expression
12.0
>>> pow(144, .5) # Built-in
12.0

The standard library random module must be imported as well.


>>> random.randint(1, 10)
5
>>> random.randint(1, 10)
4
>>> random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Life'])
'Life of Brian'
>>> random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Life'])
'Holy Grail'
The random module can be useful for shuffling cards in games, picking images at random in a slideshow GUI, performing statistical simulations,
and much more.

Sets
>>> x = set('abcde')
>>> y = set('bdxyz')
>>> x
set(['a', 'c', 'b', 'e', 'd'])
>>> 'e' in x # Membership
True
>>> x – y # Difference
set(['a', 'c', 'e'])
>>> x | y # Union
set(['a', 'c', 'b', 'e', 'd', 'y', 'x', 'z'])
>>> x & y # Intersection
set(['b', 'd'])
>>> x ^ y # Symmetric difference (XOR)
set(['a', 'c', 'e', 'y', 'x', 'z'])
>>> x > y, x < y # Superset, subset
(False, False)
>>> z = x.intersection(y) # Same as x & y
>>> z
set(['b', 'd'])
>>> z.add('SPAM') # Insert one item
>>> z
set(['b', 'd', 'SPAM'])
>>> z.update(set(['X', 'Y'])) # Merge: in-place union
>>> z
set(['Y', 'X', 'b', 'd', 'SPAM'])
>>> z.remove('b') # Delete one item
>>> z
set(['Y', 'X', 'd', 'SPAM'])
As iterable containers, sets can also be used in operations such as len, for loops, and list comprehensions. Because they are unordered, though,
they don’t support sequence operations like indexing and slicing:
>>> for item in set('abc'): print(item * 3)
...
aaa
ccc
bbb

Set operations can be coded manually in Python with other types, like lists and dictionaries.

>>> S
{1.23}
>>> S.add([1, 2, 3]) # Only mutable objects work in a set
TypeError: unhashable type: 'list'
>>> S.add({'a':1})
TypeError: unhashable type: 'dict'
>>> S.add((1, 2, 3))
>>> S # No list or dict, but tuple okay
{1.23, (1, 2, 3)}
>>> S | {(4, 5, 6), (1, 2, 3)} # Union: same as S.union(...)
{1.23, (4, 5, 6), (1, 2, 3)}
>>> (1, 2, 3) in S # Membership: by complete values
True
>>> (1, 4, 3) in S
False

>>> {x ** 2 for x in [1, 2, 3, 4]} # set comprehension


{16, 1, 4, 9}
>>> {x for x in 'spam'} # Same as: set('spam')
{'a', 'p', 's', 'm'}
>>> {c * 4 for c in 'spam'} # Set of collected expression results
{'ssss', 'aaaa', 'pppp', 'mmmm'}
>>> {c * 4 for c in 'spamham'}
{'ssss', 'aaaa', 'hhhh', 'pppp', 'mmmm'}
>>> S = {c * 4 for c in 'spam'}
>>> S | {'mmmm', 'xxxx'}
{'ssss', 'aaaa', 'pppp', 'mmmm', 'xxxx'}
>>> S & {'mmmm', 'xxxx'}
{'mmmm'}

Sets can be used to filter duplicates out of other collections. Simply convert the collection to a set, and then convert it back again (because sets
are iterable, they work in the list call here):
>>> L = [1, 2, 1, 3, 2, 4, 5]
>>> set(L)
{1, 2, 3, 4, 5}
>>> L = list(set(L)) # Remove duplicates
>>> L
[1, 2, 3, 4, 5]

>>> engineers = {'bob', 'sue', 'ann', 'vic'}


>>> managers = {'tom', 'sue'}
>>> 'bob' in engineers # Is bob an engineer?
True
>>> engineers & managers # Who is both engineer and manager?
{'sue'}
>>> engineers | managers # All people in either category
{'vic', 'sue', 'tom', 'bob', 'ann'}
>>> engineers – managers # Engineers who are not managers
{'vic', 'bob', 'ann'}
>>> managers – engineers # Managers who are not engineers
{'tom'}
>>> engineers > managers # Are all managers engineers? (superset)
False
>>> {'bob', 'sue'} < engineers # Are both engineers? (subset)
True
>>> (managers | engineers) > managers # All people is a superset of managers
True
>>> managers ^ engineers # Who is in one but not both?
{'vic', 'bob', 'ann', 'tom'}
>>> (managers | engineers) - (managers ^ engineers) # Intersection!
{'sue'}

Numeric Extensions
Finally, although Python core numeric types offer plenty of power for most applications, there is a large library of third-party open source
extensions available to address more focused needs. Because numeric programming is a popular domain for Python, you’ll find a wealth of
advanced tools.
For example, if you need to do serious number crunching, an optional extension for Python called NumPy (Numeric Python) provides advanced
numeric programming tools, such as a matrix data type, vector processing, and sophisticated computation libraries. Hardcore scientific
programming groups at places like Los Alamos and NASA use Python with NumPy to implement the sorts of tasks they previously coded in C++,
FORTRAN, or Matlab. The combination of Python and NumPy is often compared to a free, more flexible version of Matlab—you get NumPy’s
performance, plus the Python language and its libraries.
Because it’s so advanced, we won’t talk further about NumPy in this book. You can find additional support for advanced numeric programming
in Python, including graphics and plotting tools, statistics libraries, and the popular SciPy package at Python’s PyPI site, or by searching the Web.
Also note that NumPy is currently an optional extension; it doesn’t come with Python and must be installed separately.

You might also like