
函数可以做任何事情,主要的使用模式是调用参数并返回值。数学的 math模块提供了基本的数学函数,可以处理小数运算。使用Python 的Math模块, 我们可以访问依据C标准定义的不同的数学函数。这些函数提供了很多算术运算操作,如下取整 floor(x), 上取整 ceil(x), 绝对值fabs(x)等函数。下面依次描述这些函数和用法。
ceil(x)
返回一个不小于x的最小的整数。
print (math.ceil(-125.22))
print (math.ceil(620.12))
print (math.ceil(78.72))
print (math.ceil(math.pi))
输出
-125
621
79
4
copysign(x, y)
返回带y的符号的x。在支持符号零的平台,copysign(1.0, -0.0) 返回 -1.0。 (version 2.6.)
print(math.copysign(12,10))
print(math.copysign(12,-10))
输出
12.0
-12.0
fabs(x)
返回绝对值。
print(math.fabs(56))
print(math.fabs(-12.8))
print(math.fabs(12.8))
输出
56.0
12.8
12.8
factorial(x)
返回x的阶乘。
print(math.factorial(20))
print(math.factorial(12))
print(math.factorial(17))
print(math.factorial(8))
输出
2432902008176640000
479001600
355687428096000
40320
floor(x)
返回不大于x的最大的整数。
print (math.floor(18))
print (math.floor(-4.5))
print (math.floor(2.5))
输出
18
-5
2
fmod(x, y)
返回 x % y.
print(math.fmod(50,10))
print(math.fmod(10,5))
print(math.fmod(-40,24))
print(math.fmod(-15,7))
输出
0.0
0.0
-16.0
-1.0
frexp(x)
返回尾数和指数对 (m, e)
print(math.frexp(6.8))
print(math.frexp(0))
print(math.frexp(6))
输出
(0.85, 3)
(0.0, 0)
(0.75, 3)
fsum(iterable)
递归求全部所含元素的和。
num = [0.9999999, 1, 2, 3] # Sum values with fsum.
val = math.fsum(num)
print(val)
输出
6.9999999
isfinite(x)
确定真假。
print(math.isfinite(8))
print(math.isfinite(0.0)) # Python considered 0.0 as finite number print(math.isfinite(0/2))
print(math.isfinite(-100))
输出
True
True
True
True
isinf(x)
如果x是正或负无限,返回真。
print(math.isinf(8))
print(math.isinf(0.0)) # Python considered 0.0 as finite number print(math.isinf(0/2))
print(math.isinf(-100))
输出
False
False
False
False
isnan(x)
返回x是否是非数值。
print(math.isnan(10))
print(math.isnan(0.0))
print(math.isnan(0.5))
print(math.isnan(-12))
输出
False
False
False
False
ldexp(x, i)
返回 x * (2**i),它是 frexp() 反函数。
print (math.ldexp(12,8))
print (math.ldexp(-4.3,4))
print (math.ldexp(2.5,-7))
输出
3072.0
-68.8
0.01953125
modf(x)
返回x的小数部分和整数部分构成的一个元组。两个部分和x有相同的符号。整数部分作为小数返回。
print (math.modf(20.22))
print (math.pi)
输出
(0.21999999999999886, 20.0)
3.141592653589793
trunc(x)
返回x的整数部分。
print(math.trunc(4.454))
输出
4
exp(x)
自然常数e为底的指数函数:e**x。
print(math.exp(8))
print(math.exp(0.0))
print(math.exp(0.005))
输出
2980.9579870417283
1.0
1.005012520859401
pow(x, y)
返回x的y次幂。
print(math.pow(10, 2) )
print(math.pow(200, -2))
print(math.pow(2, 2))
输出
100.0
2.5e-05
4.0
sqrt(x)
返回x的平方根。
print (math.sqrt(0))
print (math.sqrt(10))
print (math.sqrt(2.5))
输出
0.0
3.1622776601683795
1.5811388300841898
pi
数学常数圆周率,圆的周长和直径的比值 (3.1415926…)。
print (math.pi)
输出
3.141592653589793
e
数学常数,自然常数 e (2.71828…)
print (math.e)
输出
2.718281828459045
Python 基础