Python的math模块提供了丰富的数学函数,用于处理各种数学运算。这个模块包含三角函数、对数函数、常数和其他有用的数学工具。
要使用math模块,首先需要导入:
import math导入后,就可以使用模块中的所有数学函数和常数了。
math模块定义了几个重要的数学常数:
import math
print("圆周率 π =", math.pi)
print("自然常数 e =", math.math.e)
print("正无穷大 =", math.inf)
print("非数字 =", math.nan)这些常数在计算中非常有用。比如计算圆的面积时要用到π,计算自然对数时要用到e。
import math
x = 3.7
y = 3.2
print("向上取整 math.ceil(3.7) =", math.ceil(x)) # 4
print("向下取整 math.floor(3.7) =", math.floor(x)) # 3
print("截断取整 math.trunc(3.7) =", math.trunc(x)) # 3import math
print("绝对值 math.fabs(-5.5) =", math.fabs(-5.5)) # 5.5math.fabs()专门用于浮点数,而内置的abs()函数可以处理所有数值类型。
import math
print("e的2次方 math.exp(2) =", math.exp(2)) # e²
print("2的3次方 math.pow(2, 3) =", math.pow(2, 3)) # 8import math
print("自然对数 math.log(10) =", math.log(10)) # 以e为底
print("以10为底 math.log10(100) =", math.log10(100)) # 2
print("以2为底 math.log2(8) =", math.log2(8)) # 3math模块提供了完整的三角函数集合:
import math
angle_degrees = 45
angle_radians = math.radians(angle_degrees) # 角度转弧度
print(f"{angle_degrees}度的弧度值:", angle_radians)
print("正弦值:", math.sin(angle_radians))
print("余弦值:", math.cos(angle_radians))
print("正切值:", math.tan(angle_radians))弧度转回角度:
import math
radians = math.pi / 4 # 45度的弧度值
degrees = math.degrees(radians)
print(f"{radians}弧度等于{degrees}度")import math
print("16的平方根:", math.sqrt(16)) # 4.0
print("8的整数平方根:", math.isqrt(8)) # 2计算两点之间的距离:
import math
# 二维空间两点距离
point1 = (1, 2)
point2 = (4, 6)
distance = math.dist(point1, point2)
print("两点距离:", distance)
# 使用hypot函数计算直角三角形的斜边
hypotenuse = math.hypot(3, 4)
print("直角边为3和4的斜边长度:", hypotenuse) # 5.0import math
a = 48
b = 18
print(f"{a}和{b}的最大公约数:", math.gcd(a, b)) # 6
# Python 3.9+ 支持最小公倍数
if hasattr(math, 'lcm'):
print(f"{a}和{b}的最小公倍数:", math.lcm(a, b))import math
print("5的阶乘:", math.factorial(5)) # 120import math
n = 5
k = 2
print(f"从{n}个中选{k}个的组合数:", math.comb(n, k)) # 10
print(f"从{n}个中选{k}个的排列数:", math.perm(n, k)) # 20import math
print("伽马函数 math.gamma(5):", math.gamma(5)) # 4! = 24import math
print("误差函数 math.erf(1):", math.erf(1))
print("互补误差函数 math.erfc(1):", math.erfc(1))这些函数用于检查数值的特殊属性:
import math
numbers = [10, float('inf'), float('-inf'), float('nan'), 0.0]
for num in numbers:
print(f"{num}: 有限={math.isfinite(num)}, 无穷={math.isinf(num)}, 非数字={math.isnan(num)}")检查两个数是否接近:
import math
a = 0.1 + 0.2
b = 0.3
print("0.1+0.2 接近 0.3:", math.isclose(a, b)) # Trueimport math
def circle_calculations(radius):
area = math.pi * math.pow(radius, 2)
circumference = 2 * math.pi * radius
return area, circumference
radius = 5
area, circumference = circle_calculations(radius)
print(f"半径为{radius}的圆:")
print(f"面积: {area:.2f}")
print(f"周长: {circumference:.2f}")import math
def solve_quadratic(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant < 0:
return "无实数解"
elif discriminant == 0:
x = -b / (2*a)
return f"唯一解: x = {x}"
else:
x1 = (-b + math.sqrt(discriminant)) / (2*a)
x2 = (-b - math.sqrt(discriminant)) / (2*a)
return f"两个解: x1 = {x1:.2f}, x2 = {x2:.2f}"
# 解方程 x² - 5x + 6 = 0
print(solve_quadratic(1, -5, 6))import math
def statistics(data):
n = len(data)
mean = sum(data) / n
variance = sum(math.pow(x - mean, 2) for x in data) / n
std_dev = math.sqrt(variance)
return {
'数量': n,
'平均值': mean,
'方差': variance,
'标准差': std_dev
}
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
stats = statistics(data)
for key, value in stats.items():
print(f"{key}: {value:.2f}")math模块只处理实数运算。如果需要处理复数,应该使用cmath模块:
import cmath
# 复数的平方根
complex_num = -4
sqrt_complex = cmath.sqrt(complex_num)
print(f"{complex_num}的平方根:", sqrt_complex) # 2j对于大量数据的数学运算,考虑使用NumPy库,它在处理数组时比math模块更快:
import math
import numpy as np
import time
# 比较math和numpy的性能
data = [i * 0.1 for i in range(10000)]
# 使用math模块
start = time.time()
result_math = [math.sin(x) for x in data]
time_math = time.time() - start
# 使用numpy
start = time.time()
result_numpy = np.sin(data)
time_numpy = time.time() - start
print(f"math模块用时: {time_math:.4f}秒")
print(f"numpy用时: {time_numpy:.4f}秒")math模块专门为浮点数数学设计,提供更专业的数学函数,而内置函数如abs()、round()等更通用。
当需要处理复数运算时,应该使用cmath模块。math模块只能处理实数。
使用math.isclose()来比较浮点数,而不是直接使用==运算符。
| 常量 | 描述 |
|---|---|
| math.e | 返回欧拉数 (2.7182...) |
| math.inf | 返回正无穷大浮点数 |
| math.nan | 返回一个浮点值 NaN (not a number) |
| math.pi | π 一般指圆周率。 圆周率 PI (3.1415...) |
| math.tau | 数学常数 τ = 6.283185...,精确到可用精度。Tau 是一个圆周常数,等于 2π,圆的周长与半径之比。 |
| 方法 | 描述 |
|---|---|
| math.acos(x) | 返回 x 的反余弦,结果范围在 0 到 pi 之间。 |
| math.acosh(x) | 返回 x 的反双曲余弦值。 |
| math.asin(x) | 返回 x 的反正弦值,结果范围在 -pi/2 到 pi/2 之间。 |
| math.asinh(x) | 返回 x 的反双曲正弦值。 |
| math.atan(x) | 返回 x 的反正切值,结果范围在 -pi/2 到 pi/2 之间。 |
| math.atan2(y, x) | 返回给定的 X 及 Y 坐标值的反正切值,结果是在 -pi 和 pi 之间。 |
| math.atanh(x) | 返回 x 的反双曲正切值。 |
| math.ceil(x) | 将 x 向上舍入到最接近的整数 |
| math.comb(n, k) | 返回不重复且无顺序地从 n 项中选择 k 项的方式总数。 |
| math.copysign(x, y) | 返回一个基于 x 的绝对值和 y 的符号的浮点数。 |
| math.cos() | 返回 x 弧度的余弦值。 |
| math.cosh(x) | 返回 x 的双曲余弦值。 |
| math.degrees(x) | 将角度 x 从弧度转换为度数。 |
| math.dist(p, q) | 返回 p 与 q 两点之间的欧几里得距离,以一个坐标序列(或可迭代对象)的形式给出。 两个点必须具有相同的维度。 |
| math.erf(x) | 返回一个数的误差函数 |
| math.erfc(x) | 返回 x 处的互补误差函数 |
| math.exp(x) | 返回 e 的 x 次幂,Ex, 其中 e = 2.718281... 是自然对数的基数。 |
| math.expm1() | 返回 Ex - 1, e 的 x 次幂,Ex,其中 e = 2.718281... 是自然对数的基数。这通常比 math.e ** x 或 pow(math.e, x) 更精确。 |
| math.fabs(x) | 返回 x 的绝对值。 |
| math.factorial(x) | 返回 x 的阶乘。 如果 x 不是整数或为负数时则将引发 ValueError。 |
| math.floor() | 将数字向下舍入到最接近的整数 |
| math.fmod(x, y) | 返回 x/y 的余数 |
| math.frexp(x) | 以 (m, e) 对的形式返回 x 的尾数和指数。 m 是一个浮点数, e 是一个整数,正好是 x == m * 2**e 。 如果 x 为零,则返回 (0.0, 0) ,否则返回 0.5 <= abs(m) < 1 。 |
| math.fsum(iterable) | 返回可迭代对象 (元组, 数组, 列表, 等)中的元素总和,是浮点值。 |
| math.gamma(x) | 返回 x 处的伽马函数值。 |
| math.gcd() | 返回给定的整数参数的最大公约数。 |
| math.hypot() | 返回欧几里得范数,sqrt(sum(x**2 for x in coordinates))。 这是从原点到坐标给定点的向量长度。 |
| math.isclose(a,b) | 检查两个值是否彼此接近,若 a 和 b 的值比较接近则返回 True,否则返回 False。。 |
| math.isfinite(x) | 判断 x 是否有限,如果 x 既不是无穷大也不是 NaN,则返回 True ,否则返回 False 。 |
| math.isinf(x) | 判断 x 是否是无穷大,如果 x 是正或负无穷大,则返回 True ,否则返回 False 。 |
| math.isnan() | 判断数字是否为 NaN,如果 x 是 NaN(不是数字),则返回 True ,否则返回 False 。 |
| math.isqrt() | 将平方根数向下舍入到最接近的整数 |
| math.ldexp(x, i) | 返回 x * (2**i) 。 这基本上是函数 math.frexp() 的反函数。 |
| math.lgamma() | 返回伽玛函数在 x 绝对值的自然对数。 |
| math.log(x[, base]) | 使用一个参数,返回 x 的自然对数(底为 e )。 |
| math.log10(x) | 返回 x 底为 10 的对数。 |
| math.log1p(x) | 返回 1+x 的自然对数(以 e 为底)。 |
| math.log2(x) | 返回 x 以 2 为底的对数 |
| math.perm(n, k=None) | 返回不重复且有顺序地从 n 项中选择 k 项的方式总数。 |
| math.pow(x, y) | 将返回 x 的 y 次幂。 |
| math.prod(iterable) | 计算可迭代对象中所有元素的积。 |
| math.radians(x) | 将角度 x 从度数转换为弧度。 |
| math.remainder(x, y) | 返回 IEEE 754 风格的 x 除于 y 的余数。 |
| math.sin(x) | 返回 x 弧度的正弦值。 |
| math.sinh(x) | 返回 x 的双曲正弦值。 |
| math.sqrt(x) | 返回 x 的平方根。 |
| math.tan(x) | 返回 x 弧度的正切值。 |
| math.tanh(x) | 返回 x 的双曲正切值。 |
| math.trunc(x) | 返回 x 截断整数的部分,即返回整数部分,删除小数部分 |
Python的math模块是进行数学计算的强大工具。它提供了:
基本数学运算函数
三角函数和对数函数
数学常数
数论和组合函数
数值检查函数
掌握math模块能够大大简化数学编程任务。对于更复杂的科学计算,可以进一步学习NumPy和SciPy库。
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!