Python
has a few other built-in functions for working with numeric types they are
listed below.
- Absolute value—abs
- Convert two numbers to a common type—coerce(x, y)
- Quotient and remainder—divmod(a, b)
- Power—pow(x, y [, z])
- Round—round(x [, n])
Absolute value—abs
The
abs(x) function takes the absolute value of any
integer, long integer, or floating
point
number:
>>>
abs(-5.0)
5.0
>>>
abs(-20L)
20L
When
applied to a complex number, this function returns the magnitude of
the number, which
is the distance from that point to the origin in the complex plane. Python calculates
the magnitude just like the length of a line in two dimensions: for a complex number
(a + bj), the magnitude is the square root of a squared plus b squared:
>>> abs(5 -
2j)
5.3851648071345037
Convert two numbers to a common type—coerce(x, y)
The
coerce function applies the previously explained
numeric conversion rules to two
numbers and returns them to you as a tuple
>>>
coerce(5,2L)
(5L, 2L)
>>>
coerce(5.5,2L)
(5.5, 2.0)
>>>
coerce(5.5,5 + 2j)
((5.5+0j), (5+2j))
Quotient and remainder—divmod(a, b)
This
function performs long division on two numbers and returns the quotient and the
remainder:
>>>
divmod(5,2)
(2, 1)
>>>
divmod(5.5,2)
(2.0, 1.5)
Power—pow(x, y [, z])
The
pow function is similar to the power (**)
operator
>>> pow(5,2)
25
>>>
pow(1.2,2.1)
1.4664951016517147
As
usual, Python coerces the two numbers to a common type if needed. If the resulting
type can’t express the correct result
>>>
pow(2.0,-1) # The coerced type is a floating point.
0.5
>>>
pow(2,-1) # The coerced type is an integer.
Traceback (innermost
last):
File “<interactive
input>”, line 1, in ?
ValueError: integer
to the negative power
An
optional third argument to pow specifies
the modulo operation to perform on
the
result:
>>> pow(2,5)
32
>>>
pow(2,5,10)
2
>>> (2 **5)
% 10
2
The
result is the same as using the power and modulo operators, but Python arrives
at the result more efficiently. (Speedy power-and-modulo is useful in some types
of cryptography.)
Round—round(x [, n])
This
function rounds a floating point number x to the nearest whole number. Optionally,
you can tell it to round to n digits
after the decimal point:
>>>
round(5.567)
6.0
>>>
round(5.567,2)
5.57
0 Comments