python库 二: math库基本介绍
math 库提供了许多对浮点数的数学运算函数。
import math
print(dir(math))
通过上面的语句,可以查看math
的属性,方法列表。
math的常用方法:
-
pow(x, y)
: 返回x的y次方
import math
y = math.pow(2,3) #返回 8.0
-
sqrt(x)
:求x的(正)平方根
import math
y = math.aqrt(4) #返回 2.0
-
factorial(x)
:取x的阶乘的值
import math
y = math.factorial(5) #返回 120, 5*4*3*2*1 = 120
-
hypot(x, y)
:得到(x2+y2)的平方根 (常用于求直角三角形斜边)
import math
y = math.hypot(3, 4) #返回 5.0
-
ldexp(x, i)
:返回x*(2**i)的值
import math
y = math.ldexp(4, 2) #返回 16.0, 4 * 2**2 = 16
-
math.e
:返回常数e
import math
y = math.e #返回 2.718281828459045
-
exp(x)
:返回常数e的x次方
import math
y = math.exp(2) #返回 7.38905609893065 等于 math.e**2
-
expm1(x)
:返回常数e的x次方的值减1
import math
y = math.expm1(2) #返回6.38905609893065 等于 math.e**2 -1
-
log(x, base)
:返回x的自然对数,默认以e为基数,base参数给定时,则以base为基数math.log2(x)
: 以2为基数math.log10(x)
: 以10为基数
import math
y = math.exp(math.e) #返回 1.0 默认以e为基数
m = math.exp(8,2) # 返回3.0
n = math.log2(8) # 返回3.0
q = math.log10(100) # 返回 2.0
-
log1p(x)
::返回x+1的自然对数(基数为e)的值
import math
y = math.log1p(math.e-1) # 返回1.0
- 三角函数 与 反三角函数:
import math
# 三角函数 (输入弧度)
angle = 30 # 30度
radian = math.radians(angle) # 角度转换成弧度, 计算公式 : 弧度 = 角度 * pi / 180
y1 = math.sin(radian) # 返回 0.5
y2 = math.cos(radian) # 返回 0.866 约等于 (二分之根号三)
y3 = math.tan(radian) # 返回 0.577 约等于 (三分之根号三)
# 反三角函数 (返回弧度)
x1 = math.asin(0.5) # 返回 pi / 6 约等于 0.523599 因为sin(pi /6) = 0.5
d1 = math.degrees(x1) #返回30.000000000000004 (计算值会有很小的差距) 弧度换角度 计算公式 : 角度 = 弧度 * 180 / pi
x2 = math.acos(0.5) # 返回 pi / 3 , cos(pi / 3) = 0.5
d2 = math.degrees(x2) # 60.00000000000001
x3 = math.atan(1) # 返回 pi / 2 ,tan(pi / 2) = 1
d3 = math.degrees(x3) # 45.0
- 双曲函数 与 反双曲函数
math.sinh
math.cosh
math.tanh
math.asinh
math.acosh
math.atanh
-
trunc(x)
:返回x的整数部分 (向中间取整,即正数向下取整,负数向上取整) -
ceil(x)
:返回x的整数部分 (向正无穷取整,即向上取整,ceil有天花板的意思) -
floor(x)
:返回x的整数部分 (向负无穷取整,即向下取整,floor有地板的意思) -
fabs(x)
:返回x的绝对值 -
modf(x)
:返回由x的小数部分和整数部分组成的元组 - 判断
import math
a = float('inf') # 正无穷
b = float('-inf') # 负无穷
c = 3
d = float('nan') # nan代表Not A Number(不是一个数),它并不等于0
#因为nan不是一个数,所以相关计算都无法得到数字。
#所有涉及nan的操作,返回的都是nan。
# isfinite(x) 如果x不是正无穷大或负无穷大,则返回True,否则返回False
y1 = math.isfinite(a) # False
y2 = math.isfinite(b) # False
y3 = math.isfinite(c) # True
# isinf(x):如果x是正无穷大或负无穷大,则返回True,否则返回False
y4 = math.isinf(a) # True
y5 = math.isinf(b) # True
y6 = math.isinf(c) # False
# isnan(x):如果x不是数字True,否则返回False
y7 = math.isnan(a) # False
y8 = math.isnan(b) # False
y9 = math.isnan(c) # False
y = math.isnan(d) # True
-
gcd(x, y)
:返回x和y的最大公约数 -
fsum(seq)
:对迭代器里的每个元素进行求和操作