引言:
math 模块提供了丰富的数学函数,适用于各种常见的数学运算。从基本的算术运算、对数和指数函数,到高级的三角函数、双曲函数和阶乘等,Python 的 math 模块都可以轻松实现。利用这些函数可以简化许多数学计算,且代码简洁易懂。
1.数学常量
math 模块定义了一些常用的数学常量,最常用的包括:
- math.pi:圆周率π(3.141592653589793)
- math.e:自然对数的底数 e(2.718281828459045)
示例:
import math
print(f"圆周率π的值: {math.pi}") # 输出: 3.141592653589793
print(f"自然对数底数e的值: {math.e}") # 输出: 2.718281828459045
2.幂运算
math 提供了幂运算的相关函数,如 pow 和 sqrt。
- math.pow(x, y):返回 x 的 y 次方。
- math.sqrt(x):返回 x 的平方根。
示例:
import math
# 计算 2 的 3 次方
print(f"2的3次方: {math.pow(2, 3)}") # 输出: 8.0
# 计算 25 的平方根
print(f"25的平方根: {math.sqrt(25)}") # 输出: 5.0
3.对数运算
math 提供了常用的对数函数,包括自然对数和以10为底的对数:
- math.log(x, base):返回以 base 为底的 x 的对数,默认 base 为 e。
- math.log10(x):返回以 10 为底的 x 的对数。
- math.log2(x):返回以 2 为底的 x 的对数。
示例:
import math
# 计算自然对数 ln(10)
print(f"ln(10): {math.log(10)}") # 输出: 2.302585092994046
# 计算以 10 为底的对数 log10(100)
print(f"log10(100): {math.log10(100)}") # 输出: 2.0
# 计算以 2 为底的对数 log2(8)
print(f"log2(8): {math.log2(8)}") # 输出: 3.0
4.三角函数
math 模块提供了各种三角函数,如正弦、余弦、正切等,单位是弧度。
- math.sin(x):返回 x 的正弦值。
- math.cos(x):返回 x 的余弦值。
- math.tan(x):返回 x 的正切值。
- math.asin(x):返回 x 的反正弦值(弧度)。
- math.acos(x):返回 x 的反余弦值(弧度)。
- math.atan(x):返回 x 的反正切值(弧度)。
示例:
import math
# 计算 π/2 的正弦值
print(f"sin(π/2): {math.sin(math.pi/2)}") # 输出: 1.0
# 计算 π 的余弦值
print(f"cos(π): {math.cos(math.pi)}") # 输出: -1.0
# 计算 π/4 的正切值
print(f"tan(π/4): {math.tan(math.pi/4)}") # 输出: 1.0
5.取整操作
math 模块提供了几种取整的方式:
- math.floor(x):返回小于或等于 x 的最大整数(向下取整)。
- math.ceil(x):返回大于或等于 x 的最小整数(向上取整)。
- math.trunc(x):返回 x 的整数部分(去除小数部分)。
示例:
import math
# 向下取整
print(f"floor(3.7): {math.floor(3.7)}") # 输出: 3
# 向上取整
print(f"ceil(3.2): {math.ceil(3.2)}") # 输出: 4
# 去除小数部分
print(f"trunc(3.7): {math.trunc(3.7)}") # 输出: 3
6.绝对值
math.fabs(x) 返回 x 的绝对值,适用于浮点数类型。
示例:
import math
# 计算 -5 的绝对值
print(f"fabs(-5): {math.fabs(-5)}") # 输出: 5.0
7.阶乘
math.factorial(x) 返回 x 的阶乘。
示例:
import math
# 计算 5 的阶乘
print(f"factorial(5): {math.factorial(5)}") # 输出: 120
8.双曲函数
math 模块还提供了双曲函数,这些函数在某些科学计算中非常重要:
- math.sinh(x):返回 x 的双曲正弦值。
- math.cosh(x):返回 x 的双曲余弦值。
- math.tanh(x):返回 x 的双曲正切值。
示例:
import math
# 计算 1 的双曲正弦值
print(f"sinh(1): {math.sinh(1)}") # 输出: 1.1752011936438014
# 计算 1 的双曲余弦值
print(f"cosh(1): {math.cosh(1)}") # 输出: 1.5430806348152437
# 计算 1 的双曲正切值
print(f"tanh(1): {math.tanh(1)}") # 输出: 0.7615941559557649
9.特殊函数
- math.gcd(x, y):返回 x 和 y 的最大公约数。
- math.isqrt(x):返回 x 的整数平方根(对于大整数非常有用)。
示例:
import math
# 计算 10 和 20 的最大公约数
print(f"gcd(10, 20): {math.gcd(10, 20)}") # 输出: 10
# 计算 9 的整数平方根
print(f"isqrt(9): {math.isqrt(9)}") # 输出: 3
10.弧度与度数的转换
- math.degrees(x):将弧度转换为度数。
- math.radians(x):将度数转换为弧度。
示例:
import math
# 将 π/2 弧度转换为度数
print(f"degrees(π/2): {math.degrees(math.pi/2)}") # 输出: 90.0
# 将 180 度转换为弧度
print(f"radians(180): {math.radians(180)}") # 输出: 3.141592653589793