数学运算模块:math与cmath
作者:Shawn
python3.7
文档:
https://docs.python.org/3/library/math.html
https://docs.python.org/3/library/cmath.html
- 数学运算模块:math与cmath
- math模块
- 常规部分
- math.ceil(x)
- math.copysign(x, y)
- math.fabs(x)
- math.factorial(x)
- math.floor(x)
- math.fmod(x, y)
- math.frexp(x)
- math.fsum(iterable)
- math.gcd(a, b)
- math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
- math.isfinite(x)
- math.isinf(x)
- math.isnan(x)
- math.ldexp(x, i)
- math.modf(x)
- math.remainder(x, y)
- math.trunc(x)
- 指数、对数部分
- 三角函数部分
- 特殊函数部分
- 常数部分
- 常规部分
- cmath模块
- math模块
math模块
- 其实不起眼的math里加进去了很多黑科技。
常规部分
math.ceil(x)
- 向上取整
>>> import math
>>> math.ceil(0.0)
0
>>> math.ceil(0.1)
1
>>> math.ceil(41.1)
42
math.copysign(x, y)
- copy符号
- 返回x的绝对值和y的符号(对不起,这是我和他的孩子)
>>> import math
>>> math.copysign(1, -0.0)
-1.0
>>> math.copysign(-1, 0.0)
1.0
>>> math.copysign(-1, -0.0)
-1.0
>>> math.copysign(1, 0)
1.0
math.fabs(x)
- 返回绝对值
- math.fabs()与内置函数abs()的区别:
- fabs需要import math后才能调用,abs可以直接使用
- abs可以用于复数而fabs不可以。
>>> math.fabs(-8)
8.0
>>> abs(-8)
8
>>> abs(1+1.0j)
1.4142135623730951
>>> math.fabs(1+1.0j)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
math.fabs(1+1.0j)
TypeError: can't convert complex to float
math.factorial(x)
- 这个函数竟然可以返回x!
- 2乘3竟然等于3!
- (返回x的阶乘)
>>> math.factorial(3)
6
>>> math.factorial(10)
3628800
math.floor(x)
- 向下取整
>>> math.floor(0.0)
0
>>> math.floor(0.1)
0
>>> math.floor(-0.1)
-1
>>> math.floor(42.9)
42
math.fmod(x, y)
- 取模运算
- 与路人运算符号%的区别:
- fmod默认返回浮点数
- 对于x、y符号一致时,%与fmod结果一致
- 但x、y符号不一致时,结果不同
- 详见取模运算
>>> 3%2
1
>>> 3%-2
-1
>>> -3%2
1
>>> 3.1%3
0.10000000000000009
>>> math.fmod(3, 2)
1.0
>>> math.fmod(3, -2)
1.0
>>> math.fmod(-3,