python math模块详解

python math模块详解

除了 ceil 和 floor 函数返回的结果是 int 类型之外, 其他的返回的都是 float 类型

import math

# 1.math.ceil(x) 向上取整数, 和内置函数 round 比较
res = math.ceil(2.0000023) # note: 精度损耗
print(res)  # 3

# 2.math.floor(x) 向下取整操作, 和内置函数 round 比较
res = math.floor(45.9123)
print(res)  # 45

# 3.math.pow(x, y) 计算一个数值的 n 次方,返回类型 float
# note: 与内置的 pow 函数不同, 没有第三个参数
res = math.pow(2, 3)
print(res)  # 8.0

# 4.math.sqrt(x) 开平方运算,返回类型 float
res = math.sqrt(100)
print(res)  # 10.0

# 5.math.fabs(x) 计算一个数的绝对值,返回类型 float
res = math.fabs(-5634)
print(res)  # 5634.0

# 6.math.modf(x) 将一个数值拆分为整数和小数两部分, 并以元组返回
res = math.modf(1333.99990)
print(res)  # (0.9999000000000251, 1333.0)

# 7.math.copysign(x, y) 将第二个参数的 符号 赋给 第一个参数,返回类型 float
res = math.copysign(13, -66667)
print(res)  #-13.0

# 8.math.fsum(iterable) 对容器中的数据进行求和,返回类型 float
listvar = [234, 242, 4, 2, 42, 42, 4]
res = math.fsum(listvar)
print(res)  # 570.0

# 9.math.pi 圆周率常数 pi
res = math.pi
print(res)  # 3.141592653589793

猜你喜欢

转载自www.cnblogs.com/trent-fzq/p/10988377.html