马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Python数学库(math)使用指南
目录
- 模块导入
- 数学常量
- 常用数学函数
- 示例代码
- 注意事项
- 官方文档
一、模块导入
math是Python内置的一个标准库,它包罗了很多执行复杂数学运算的函数,如三角函数、对数函数、指数函数等。
二、数学常量
常量描述近似值math.pi圆周率π3.141592653math.e自然对数的底数e2.718281828math.tau2π (Python 3.6+)6.283185307math.inf正无穷大∞math.nan非数字值NaN
- math.log(x[, base]): 自然对数。import math
- # 计算自然对数log_val = math.log(2.71828)log_base_10_val = math.log(100, 10)print(log_val) # 输出约 1.0print(log_base_10_val) # 输出 2.0
复制代码 三、常用数学函数
1.数值运算
函数描述示例math.ceil(x)向上取整ceil(3.2) -> 4math.floor(x)向下取整floor(3.8) -> 3math.factorial(x)阶乘计算factorial(5) -> 120math.gcd(*integers)最大公约数(Python 3.5+)gcd(12, 18) -> 6math.fabs(x)绝对值(浮点型)fabs(-3.5) -> 3.5
- import math
- # 向上取整result = math.ceil(3.14)print(result) # 输出 4
复制代码
- math.floor(x): 向下取整。
- import math
- # 向下取整result = math.floor(3.14)print(result) # 输出 3
复制代码 2.幂与对数
函数描述示例math.pow(x, y)x的y次幂pow(2, 3) -> 8.0math.sqrt(x)平方根sqrt(9) -> 3.0math.exp(x)e的x次幂exp(1) -> 2.71828...math.log(x[, base])对数函数(默认自然对数)log(100, 10) -> 2.0
- import math
- # 计算平方根result = math.sqrt(16)print(result) # 输出 4.0
复制代码
- math.pow(x, y): 计算 x 的 y 次幂
- import math
- # 计算幂result = math.pow(2, 3)print(result) # 输出 8.0
复制代码
- math.trunc(x): 截断小数部门。
- import math
- # 截断小数result = math.trunc(3.14)print(result) # 输出 3
复制代码 3.三角函数
函数描述math.sin(x)正弦函数math.cos(x)余弦函数math.tan(x)正切函数math.degrees(x)弧度转角度math.radians(x)角度转弧度
- math.sin(x), math.cos(x), math.tan(x): 正弦、余弦、正切函数
- import math
- # 计算角度对应的三角函数值angle = math.pi / 4sin_val = math.sin(angle)cos_val = math.cos(angle)tan_val = math.tan(angle)print(sin_val) # 输出约 0.707print(cos_val) # 输出约 0.707print(tan_val) # 输出约 1.0
复制代码
- math.asin(x), math.acos(x), math.atan(x): 反三角函数
- import math
- # 计算反三角函数值arcsin_val = math.asin(0.707)arccos_val = math.acos(0.707)arctan_val = math.atan(1.0)print(arcsin_val) # 输出约 0.785print(arccos_val) # 输出约 0.785print(arctan_val) # 输出约 0.785
复制代码
- import math
- # 弧度转角度radian = math.pi / 4degrees = math.degrees(radian)print(degrees) # 输出 45.0
复制代码
- math.radians(x): 角度转弧度。
- import math
- # 角度转弧度degree = 45radians = math.radians(degree)print(radians) # 输出约 0.785
复制代码 四、特殊函数
函数描述Python版本要求math.comb(n, k)组合数计算 C(n,k)3.10+math.prod(iterable)可迭代对象的乘积3.8+ 五、示例代码
- import math
- # 圆周率pi_val = math.piprint(pi_val) # 输出约 3.14159
复制代码
- import math
- # 自然对数的底数e_val = math.eprint(e_val) # 输出约 2.71828
复制代码 注意事项
- 版本兼容性:
- 部门函数如math.comb()需要Python 3.10+
- 组合数计算在旧版本中可使用itertools.combinations
- 数值精度:
- # 浮点数精度问题
- print(0.1 + 0.2 == 0.3) # 输出:False
复制代码 - 替代运算符:
- # 优先使用内置运算符
- print(2 ** 0.5) # 替代math.sqrt(2)
复制代码 官方文档
- Python 3.12 math模块文档(https://docs.python.org/3/library/math.html)
- 数学函数速查表(https://www.programiz.com/python-programming/modules/math)
掌握数学库的使用可以明显提升数值计算的开发服从,建议联合详细项目需求机动选用合适函数。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |