Python的math库是一个包含许多数学函数的库,这些函数可以用来处理各种数学问题,本文介绍math库中常用的函数,并给出相应的案例供大家学习。

计算绝对值
import math
num = -5
print(math.fabs(num)) # 输出:5.0
向上取整
import math
num = 4.7
print(math.ceil(num)) # 输出:5
计算平方根
import math
num = 9
print(math.sqrt(num)) # 输出:3.0
向下取整
import math
num = 4.7
print(math.floor(num)) # 输出:4
计算幂运算
import math
base = 2
exponent = 3
print(math.pow(base, exponent)) # 输出:8.0
计算对数
import math
num = 10
print(math.log(num)) # 输出:2.302585092994046
计算阶乘
import math
num = 5
print(math.factorial(num)) # 输出:120
计算三角函数sin
import math
radians = math.pi / 2
print(math.sin(radians)) # 输出:1.0
计算三角函数cos
import math
radians = math.pi / 2
print(math.cos(radians)) # 输出:6.123233995736766e-17
计算三角函数tan
import math
radians = math.pi / 4
print(math.tan(radians)) # 输出:1.0
fmod()返回余数
import math
math.fmod(10,3)
gcd()最大公约数
返回整数 a 和 b 的最大公约数。如果 a 或 b 之一非零,则 gcd(a, b) 的值是能同时整除 a 和 b 的最大正整数。gcd(0, 0) 返回 0。
import math
math.gcd(10,15)
exp()返回 e 次 x 幂
其中 e = 2.718281... 是自然对数的基数。
import math
math.exp(2)
modf()返回小数和整数部分
import math
math.modf(3.71828)
以上是math库常用的函数,学会这些常用的函数可以提高我们编程的效率。