python math模块

介绍

math模块封装数学相关的常量、函数

常量

\pi:math.pi

自然数:math.e

无穷:math.inf

不是数字:math.nan

常用函数

print("10的绝对值:",math.fabs(10))
print("-23的绝对值:",math.fabs(-23))

# python内置的绝对值函数
print("10的绝对值:",abs(10))
print("-23的绝对值:",abs(-23))
print("-23.5的绝对值:",abs(-23.5))

print("取模-----------")
print("13%9 = ",13%9) # 4
print("math取模13,9 = ",math.fmod(13,9)) # 4.0

print("求和-----------")

nums = [1,2,3,4,5,6,7,8,9,10]
# 做累加操作,55
print("python内置sum():",sum( nums )) # 55
print("math.fsum():",math.fsum( nums )) # 55.0,传入的是整数,返回的是浮点数

print("天花板函数----------------")

print("3.14执行天花板函数:",math.ceil(3.14)) # 4
print("3.9执行天花板函数:",math.ceil(3.9)) # 4
print("-3.14执行天花板函数:",math.ceil(-3.14)) # -3

print("地板函数-------------------")

print("3.14执行地板函数:",math.floor(3.14)) # 3
print("3.9执行地板函数:",math.floor(3.9)) # 3
print("-3.14执行地板函数:",math.floor(-3.14)) # -4


print("x的y次幂------------------")

print("2的8次方:",math.pow(2,8)) # 256.0
print("3的2次方:",math.pow(3,2)) # 9.0
print("2的平方根:",math.sqrt(2)) # 1.4142135623730951

原文出处:/show_1GW12WvxItvV.html