Python内置函数(49)——pow

英文文档:

pow(x, y[, z])
Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z). The two-argument form pow(x, y) is equivalent to using the power operator: x**y.
The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01. If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative.

 

说明:
  1. 函数有两个必需参数x,y和一个可选参数z,结果返回x的y次幂乘(相当于x**y),如果可选参数z有传入值,则返回幂乘之后再对z取模(相当于pow(x,y)%z)。
>>> pow(2,3)
8
>>> 2**3
8

>>> pow(2,3,5)
3
>>> pow(2,3)%5
3

   2. 所有的参数必须是数值类型。

>>> pow('2',3)
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    pow('2',3)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

  3. 如果x,y有一个是浮点数,则结果将转换成浮点数。

>>> pow(2,0.1)
1.0717734625362931

  4. 如果x,y都是整数,则结果也是整数,除非y是负数;如果y是负数,则结果返回的是浮点数,浮点数不能取模,所有可选参数z不能传入值。

>>> pow(10,2)
100
>>> pow(10,-2)
0.01
>>> pow(10,-2,3)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    pow(10,-2,3)
ValueError: pow() 2nd argument cannot be negative when 3rd argument specified

  5. 如果可选参数z传入了值,x,y必须为整数,且y不能为负数。

>>> pow(2,3,5)
3

>>> pow(10,0.1,3)
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    pow(10,0.1,3)
TypeError: pow() 3rd argument not allowed unless all arguments are integers

>>> pow(10,-2,3)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    pow(10,-2,3)
ValueError: pow() 2nd argument cannot be negative when 3rd argument specified

 

posted @ 2016-11-10 09:33  十月狐狸  阅读(3336)  评论(0编辑  收藏  举报