Online Book Reader

Home Category

Learning Python - Mark Lutz [87]

By Root 1328 0
if your Python code must deal with things like network packets or packed binary data produced by a C program. Be aware, though, that bitwise operations are often not as important in a high-level language such as Python as they are in a low-level language such as C. As a rule of thumb, if you find yourself wanting to flip bits in Python, you should think about which language you’re really coding. In general, there are often better ways to encode information in Python than bit strings.

* * *

Note


In the upcoming Python 3.1 release, the integer bit_length method also allows you to query the number of bits required to represent a number’s value in binary. The same effect can often be achieved by subtracting 2 from the length of the bin string using the len built-in function we met in Chapter 4, though it may be less efficient:

>>> X = 99

>>> bin(X), X.bit_length()

('0b1100011', 7)

>>> bin(256), (256).bit_length()

('0b100000000', 9)

>>> len(bin(256)) - 2

9

* * *

Other Built-in Numeric Tools

In addition to its core object types, Python also provides both built-in functions and standard library modules for numeric processing. The pow and abs built-in functions, for instance, compute powers and absolute values, respectively. Here are some examples of the built-in math module (which contains most of the tools in the C language’s math library) and a few built-in functions at work:

>>> 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)

The sum function shown here works on a sequence of numbers, and min and max accept either a sequence or individual arguments. There are a variety of ways to drop the decimal digits of floating-point numbers. We met truncation and floor earlier; we can also round, both numerically and for display purposes:

>>> 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')

As we saw earlier, the last of these produces strings that we would usually print and supports a variety of formatting options. As also described earlier, the second to last test here will output (3, 2, 2.57) if we wrap it in a print call to request a more user-friendly display. The last two lines still differ, though—round rounds a floating-point number but still yields a floating-point number in memory, whereas string formatting produces a string and doesn’t yield a modified number:

>>> (1 / 3), round(1 / 3, 2), ('%.2f' % (1 / 3))

(0.33333333333333331, 0.33000000000000002, '0.33')

Interestingly, there are three ways to compute square roots in Python: using a module function, an expression, or a built-in function (if you’re interested in performance, we will revisit these in an exercise and its solution at the end of Part IV, to see which runs quicker):

>>> import math

>>> math.sqrt(144) # Module

12.0

>>> 144 ** .5 # Expression

12.0

>>> pow(144, .5) # Built-in

12.0

>>> math.sqrt(1234567890) # Larger numbers

35136.418286444619

>>> 1234567890 ** .5

35136.418286444619

>>> pow(1234567890, .5)

35136.418286444619

Notice that standard library modules such as math must be imported, but built-in functions such as abs and round are always available without imports. In other words, modules are external components, but built-in functions live in an implied namespace that Python automatically searches to find names used

Return Main Page Previous Page Next Page

®Online Book Reader