Python标准库math
math所提供的数学常量
| pi | 数学常量 pi,所属的变量空间为标准库math |
|---|---|
| e | 数学常量 e,e即自然常数,所属的变量空间为标准库math |
math库中常用的函数
三角函数
| 函数名 | 格式 | 功能 |
|---|---|---|
| sin | sin(x) | 返回的x弧度的正弦值 |
| cos | cos(x) | 返回的x弧度的余弦值 |
| tan | tan(x) | 返回的x弧度的正切值 |
| asin | asin(x) | 返回x的反正弦弧度值。 |
| acos | acos(x) | 返回x的反余弦弧度值。 |
| atan | atan(x) | 返回x的反正切弧度值。 |
| atan2 | atan2(x,y) | 返回给定的 X及Y坐标值的反正切值。 |
| degrees | degrees(x) | degrees() 将弧度x转换为角度。 |
| radians | radians(x) | 返回一个角度的弧度值。 |
数值函数
| 函数名 | 格式 | 功能 |
|---|---|---|
| exp | exp( x ) | 返回x的指数\(e^x\)。 |
| pow | pow(x,y) | pow() 方法返回(x的y次方) 的值。 |
| sqrt | sqrt(x) | sqrt() 方法返回数字x的平方根。 |
| hypot | hypot(x, y) | hypot() 返回欧几里德范数 sqrt(x*x + y*y)。 |
| modf | modf(x) | modf()方法返回x的整数部分与小数部分 |
| fabs | fabs(x) | fabs()方法返回数字x的绝对值 |
| log | log(x) | log() 方法返回x的自然对数。 |
| log10 | log10(x) | log10()方法返回以10为基数的x对数。 |
| copysign | copysign(x,y) | 返回模为|x|,符号为sign(y)的数值 |
| factorial | factorial(x) | 计算x! |
| fmod | fmod(x,y) | x对y求模,实现是以C库为底,返回更为精确的浮点数 |
| frexp | frexp(x) | 返回一个二元组,分别是x的指数部分与尾数部分 (m, e) ,x == m * 2**e |
| fsum | fsum(x) | 返回一个求和后得到的浮点数。 |
其他的函数
- math.isinf(x)
x 是不是正负无穷大.
- math.isnan(x)
x是不是NaN(不是一个数字),
- math.ldexp(x, i)
Return x * (2**i). 和frexp()相反.
- math.trunc(x)
Return x的整数部分(truncated 截断)int(x)
- math.expm1(x)
Return e**x - 1. x非常小的时候使用,会更精确。
- math.log1p(x)
Return log(1+x)以e为底,x近似于0时更准确
(双曲线方法)Hyperbolic functions
- math.acosh(x)
Return the inverse hyperbolic cosine of x.
- math.asinh(x)
Return the inverse hyperbolic sine of x.
- math.atanh(x)
Return the inverse hyperbolic tangent of x.
- math.cosh(x)
Return the hyperbolic cosine of x.
- math.sinh(x)
Return the hyperbolic sine of x.
- math.tanh(x)
Return the hyperbolic tangent of x.
(特殊方法)Special functions
math.erf(x)
math.erfc(x)
math.gamma(x)
math.lgamma(x)
Python标准库cmath
标准库math缺乏对于复数的操作,这时候需要引入另外的一个Python内置的标准库cmath。
如下:
>>> import math
>>> math.sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
>>> import cmath
>>> cmath.sqrt(-1)
1j 可以看到math.sqrt传入的参数为负数时,因为操作范围在实数会报错;cmath.sqrt操作范围在复数所以传入参数为-1返回一个虚数。
cmath拥有与math相同绝大多数函数,只是操作范围在复数域内;以下仍有几个函数值得记忆:
- cmath.phase(x) :
equal to math.atan2(x.imag, x.real).
- cmath.polar(x) :
equal to (abs(x), phase(x)).
- cmath.rect(r, phi):
equal to r * (math.cos(phi) + math.sin(phi)*1j).
Return (x.imag+x.real*j)