数学函数模块
导入
import math #(导入数学模块)
from math import * #(不推荐这种方式导入)
from math import sqrt, pow #(需要哪些导入哪些)
使用math模块
#向上取整 math.ceil
>>> math.ceil(15.19872684)
16
>>> math.ceil(-15.19872684)
-15
#向下取整 math.floor
>>> math.floor(15.19872684)
15
>>> math.floor(-15.19872684)
-16
#截断取整 math.trunc
>>> math.trunc(15.19872684)
15
>>> math.trunc(-15.19872684)
-15
#四舍五入 round(number[,ndigits]) ndigits是可选参数,保留小数点几位
#(不是math函数,是公共函数)
>>> round(15.19872684)
15
>>> round(15.19872684,2)
15.2
>>> round(15.19872684,-1) #这个注意!!!!
20.0
>>>
>>> round(-15.19872684)
-15
>>> round(-15.9872684)
-16
>>> round(15.9872684)
16
##这里有个小Bug
>>> round(7.1125,3)
7.112
#求平方 math.pow
math.pow(2, 3) #2的3次方
8.0
>>> math.pow(3, 2) #3的2次方
9.0
#求开方
>>> math.sqrt(9)
3.0
# e 的几次方
>>> math.exp(1)
2.718281828459045
>>> math.exp(2)
7.38905609893065
#求对数值 math.log(x [,base]) base的默认值为e
>>> math.log(2.718281828459045)
1.0
>>> math.log(4,2) # 2 的几次方为 4
2.0
>>> math.log2(8) # 2 的几次方为 8 可以看出文件有多少位
3.0
>>> math.log10(100) # 10 的几次方为100
2.0
>>>
# π 的常量
>>> math.pi
3.141592653589793
#绝对值 math.fabs()
>>> math.fabs(156)
156.0
>>> math.fabs(-156)
156.0