math模块
-
.ceil() —— 以浮点数的方式返回向上圆整的结果
>>> math.ceil(1.23) 2
-
.floor() —— 以浮点数的方式返回向下圆整的结果
>>> math.floor(2.13) 2
-
.sqrt() —— 返回平方根;不能用于复数
>>> math.sqrt(9) 3.0 ----------------- >>> math.sqrt(-3) Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> math.sqrt(-3) ValueError: math domain error
在有些平台上可能会是:
>>> math.sqrt(-3) nan
注:nan具有特殊含义,指的是“not a number”
-
.log(b, a) —— 以a为底,b为真数的对数
>>> math.log(10,10) 1.0 >>> math.e 2.718281828459045 >>> math.log(10,math.e) 2.302585092994046
其中,math.e 即为数学中的自然数e
引入异常处理机制:import math try: a = eval(input('请输入底数:')) b = eval(input('请输入真数:')) c = math.log(b, a) except ValueError: if a <= 0 and b > 0: print('底数不能小于等于0') elif b <= 0 and a > 0: print('真数不能小于等于0') elif a <= 0 and b <= 0: print('真数和底数都不能小于等于0') except ZeroDivisionError: print('底数不能为1') except NameError: print('输入必须为实数') else: print(c)
-
.gcd(a, b) —— 求最大公约数
>>> math.gcd(4, 6) 2
等价于
def gcd(a, b): return (a if b == 0 else gcd(b, a % b))
-
.factorial(n) —— 求阶乘n!
>>> import math >>> math.factorial(3) 6 >>> math.factorial(0) 1
cmath模块
正如介绍sqrt时所示,用sqrt处理复数会出错。
-
cmath是Python标准库专门用于处理复数的模块。
-
在处理复数的开方运算时,因为结果是复数,math会报错,应使用cmath模块处理负数开方运算
>>> import cmath >>> cmath.sqrt(-1) 1j >>> math.sqrt(-10) Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> math.sqrt(-10) ValueError: math domain error >>> cmath.sqrt(-10) 3.1622776601683795j
注:应避免使用from…import…而采用math.sqrt或camth.sqrt的方法调用,若math与cmath均使用此方法导入模块,将无法使用常规sqrt,这是很隐蔽的名称冲突。
Python没有专门表示虚数的类型,而是将虚数视为实部为零的复数。