Page 177 - Learning Python
P. 177

www.it-ebooks.info

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                 # Module
>>> math.sqrt(144)              # Expression
12.0                            # Built-in
>>> 144 ** .5
12.0
>>> pow(144, .5)
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 func-
tions such as abs and round are always available without imports. In other words, mod-
ules are external components, but built-in functions live in an implied namespace that

Python automatically searches to find names used in your program. This namespace

corresponds to the module called builtins in Python 3.0 (__builtin__ in 2.6). There

126 | Chapter 5: Numeric Types
   172   173   174   175   176   177   178   179   180   181   182