1. 准备环境 #
math 为 Python 内置标准库,无需安装。但在运行示例前,请确认命令行中的 Python 可执行文件名:
# 说明:在 Windows PowerShell 中查看 Python 版本
python --version# 说明:在 macOS 终端中查看 Python 版本
python3 --version若系统同时安装 python 与 python3,运行脚本时可参考:
# 说明:在 Windows PowerShell 中运行 demo.py
python demo.py# 说明:在 macOS 终端中运行 demo.py
python3 demo.py2. 导入与基本调用 #
# 说明:导入 math 模块,使用其中的函数与常量
import math
# 说明:打印圆周率常量
print(math.pi)3. 常用数学常量 #
# 说明:导入 math 模块,准备查看常量
import math
# 说明:输出圆周率 π
print('π =', math.pi)
# 说明:输出自然常数 e
print('e =', math.e)
# 说明:输出正无穷大
print('正无穷 =', math.inf)
# 说明:输出非数字 NaN
print('非数字 =', math.nan)4. 数值基础操作 #
适用于绝对值、取整、阶乘等常见需求。
# 说明:导入 math 模块,使用数值函数
import math
# 说明:计算绝对值
print('fabs(-5.5) =', math.fabs(-5.5))
# 说明:计算阶乘
print('factorial(5) =', math.factorial(5))
# 说明:向下取整
print('floor(3.7) =', math.floor(3.7))
# 说明:向上取整
print('ceil(-3.2) =', math.ceil(-3.2))
# 说明:截断取整
print('trunc(-3.7) =', math.trunc(-3.7))5. 幂与对数函数 #
预备知识:指数代表重复乘法;对数是指数的反运算;平方根寻找“平方后得到原数”的值。
# 说明:导入 math 模块,准备演示幂与对数
import math
# 说明:计算平方根
print('sqrt(16) =', math.sqrt(16))
# 说明:执行幂运算
print('pow(2, 3) =', math.pow(2, 3))
# 说明:计算指数函数 e^x
print('exp(2) =', math.exp(2))
# 说明:计算自然对数
print('log(10) =', math.log(10))
# 说明:计算以 10 为底的对数
print('log10(100) =', math.log10(100))
# 说明:计算以 2 为底的对数
print('log2(8) =', math.log2(8))6. 三角函数与弧度 #
一整圈为 2pi 弧度 = 360°,因此 1° = (pi/180) 弧度。若你更熟悉角度,先用
math.radians()做转换。
# 说明:导入 math 模块,准备演示三角函数
import math
# 说明:将角度转换为弧度
print('180° 对应弧度 =', math.radians(180))
# 说明:将弧度转换为角度
print('π 弧度对应角度 =', math.degrees(math.pi))
# 说明:准备一个 30° 的弧度角
angle = math.radians(30)
# 说明:计算正弦值
print('sin 30° =', math.sin(angle))
# 说明:计算余弦值
print('cos 30° =', math.cos(angle))
# 说明:计算正切值
print('tan 30° =', math.tan(angle))
# 说明:计算反正弦并转为角度
print('asin 0.5 =', math.degrees(math.asin(0.5)))
# 说明:计算反余弦并转为角度
print('acos 0.5 =', math.degrees(math.acos(0.5)))
# 说明:计算反正切并转为角度
print('atan 1 =', math.degrees(math.atan(1)))7. 特殊但常用的函数 #
# 说明:导入 math 模块,准备调用常用工具函数
import math
# 说明:计算最大公约数
print('gcd(12, 18) =', math.gcd(12, 18))
# 说明:计算最小公倍数
print('lcm(12, 18) =', math.lcm(12, 18))
# 说明:判断数字是否有限
print('isfinite(10) =', math.isfinite(10))
# 说明:判断数字是否为无穷
print('isinf(float("inf")) =', math.isinf(float('inf')))
# 说明:判断数字是否为 NaN
print('isnan(float("nan")) =', math.isnan(float('nan')))8. 实战 #
8.1 计算圆的面积与周长 #
# 说明:导入 math 模块,准备编写辅助函数
import math
# 说明:定义函数,用于返回圆的面积与周长
def circle_calculations(radius: float) -> tuple[float, float]:
# 说明:根据 πr^2 计算面积
area = math.pi * math.pow(radius, 2)
# 说明:根据 2πr 计算周长
circumference = 2 * math.pi * radius
# 说明:返回面积与周长
return area, circumference
# 说明:脚本入口,设置半径并打印结果
if __name__ == '__main__':
# 说明:设定半径为 5
r = 5
# 说明:调用函数获取面积与周长
area, length = circle_calculations(r)
# 说明:打印面积
print(f'半径为 {r} 的圆:面积 {area:.2f}, 周长 {length:.2f}')8.2 解一元二次方程 #
# 说明:导入 math 模块,准备求解二次方程
import math
# 说明:定义函数,按照判别式分类讨论
def solve_quadratic(a: float, b: float, c: float) -> None:
# 说明:计算判别式 Δ = b^2 - 4ac
discriminant = b ** 2 - 4 * a * c
# 说明:判别式小于 0,没有实数解
if discriminant < 0:
print('无实数解')
# 说明:判别式等于 0,只有一个实数解
elif discriminant == 0:
# 说明:计算唯一解
x = -b / (2 * a)
print(f'唯一解:x = {x:.2f}')
# 说明:判别式大于 0,有两个不同实数解
else:
# 说明:先计算判别式的平方根
root = math.sqrt(discriminant)
# 说明:计算第一个解
x1 = (-b + root) / (2 * a)
# 说明:计算第二个解
x2 = (-b - root) / (2 * a)
print(f'两个解:x1 = {x1:.2f}, x2 = {x2:.2f}')
# 说明:脚本入口,代入示例参数
if __name__ == '__main__':
# 说明:求解 x^2 - 5x + 6 = 0
solve_quadratic(1, -5, 6)8.3 计算两点之间的距离 #
# 说明:导入 math 模块,准备计算两点距离
import math
# 说明:定义 distance 函数,返回两点间距离
def distance(x1: float, y1: float, x2: float, y2: float) -> float:
# 说明:套入欧几里得距离公式
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
# 说明:脚本入口,调用函数并打印结果
if __name__ == '__main__':
# 说明:计算 (1,1) 与 (4,5) 的距离
result = distance(1, 1, 4, 5)
# 说明:输出计算结果
print(f'两点间距 = {result:.2f}')9. 常见错误与调试 #
# 说明:导入 math 模块,准备演示异常处理
import math
# 说明:尝试对负数开平方
try:
print(math.sqrt(-1))
# 说明:捕获 ValueError 并输出错误信息
except ValueError as err:
print(f'出现数学错误:{err}')