从零开始的Python世界生活——内置模块(Math)

从零开始的Python世界生活------内置模块(Math)

Python的math模块提供了丰富的数学函数和常数,支持基本的数学运算、三角函数、对数、指数等,适用于科学计算和工程应用。

数学常量:

注意math模块的常量是以双精度浮点数存储的,所以通常只有15到17位有效数字的精度,如果需要更高的精度推荐使用 decimal 模块或 mpmath

π(圆周率)

python 复制代码
import math
print(math.pi)
#运行结果:3.141592653589793

τ(2π)

一些数学家提倡使用τ代替π,认为τ更直观,特别是在涉及圆的角度和周期性问题时

python 复制代码
import math
print(math.tau)
#运行结果:6.283185307179586

e(欧拉数)

python 复制代码
import math
print(math.e)
#运行结果:2.718281828459045

infinity(无穷大)

python 复制代码
import math
print(math.inf)
#运行结果:inf

Not a Number(不是一个数字)

未定义或不可表示的值,如0除以0的结果,负数的平方根(在实数范围内),可以在数据分析和科学计算中用来标记缺失或无效的数据点

python 复制代码
import math
print(math.nan)
#运行结果:nan

数学函数:

1. 基本数学函数:

math.fsum(iterable) 返回可迭代对象的浮点数和,相比sum(iterable)具有更高的精度。

python 复制代码
import math
iterable=[0.1,0.2,0.3]
print(math.fsum(iterable))
#运行结果:0.6

2. 幂和对数

幂函数

  • math.pow(x, y):返回x**y
  • math.exp(x):返回 e**x

对数函数

  • math.log(x[, base]):返回 logba**se (x),如果未指定基数,则返回自然对数。
  • math.log10(x):返回以 10 为底的对数。
  • math.log2(x):返回以 2 为底的对数。

3. 三角函数

基本三角函数

  • math.sin(x):返回 sin(x)。
  • math.cos(x):返回 cos(x)。
  • math.tan(x):返回 tan(x)。

反三角函数

  • math.asin(x):返回 arcsin(x)。
  • math.acos(x):返回 arccos(x)。
  • math.atan(x):返回 arctan(x)。
  • math.atan2(y, x):返回 arctan(y /x)。

4. 超越函数

双曲函数

  • math.sinh(x):返回双曲正弦。
  • math.cosh(x):返回双曲余弦。
  • math.tanh(x):返回双曲正切。

反双曲函数

  • math.asinh(x):返回反双曲正弦。
  • math.acosh(x):返回反双曲余弦。
  • math.atanh(x):返回反双曲正切。

5. 其他函数

阶乘

math.factorial(x):返回x的阶乘

python 复制代码
import math
x = 3 
print(math.factorial(x))# 运行结果 :6

取整和舍入

math.ceil(x):返回大于或等于 x 的最小整数。

math.floor(x):返回小于或等于 x 的最大整数。

math.trunc(x):返回 x 的整数部分。

python 复制代码
import math
x = 1.5
print(math.ceil(x))#运行结果:2
print(math.floor(x))#运行结果:1
print(math.trunc(x))#运行结果:1

平方根和绝对值

math.sqrt(x):返回 x 的平方根。

math.isqrt(x):返回 x 的平方根的整数部分。

python 复制代码
import math
x = 3
print(math.sqrt(x))#运行结果:1.7320508075688772
print(math.isqrt(x))#运行结果:1

math.fabs(x)

返回 x 的绝对值,注意返回的是浮点数,故用于获得浮点数的绝对值,获得整数绝对值,使用内置函数abs(x)

python 复制代码
import math
x = -1
print(math.fabs(x)) #运行结果:1.0
print(abs(x))#运行结果:1

6. 组合和排列(仅在 Python 3.8 及以上版本可用)

math.comb(n, k):返回从 n 个元素中选择 k 个元素的组合数。

math.perm(n, k):返回从 n 个元素中选择 k 个元素的排列数。

python 复制代码
import math
n, k = 5, 3
print(math.comb(n,k))#运行结果:10
print(math.perm(n,k))#运行结果:60

入门之道,就在其中

相关推荐
basketball61614 分钟前
Python torchvision.transforms 下常用图像处理方法
开发语言·图像处理·python
兔子蟹子19 分钟前
Java集合框架解析
java·windows·python
宁酱醇23 分钟前
各种各样的bug合集
开发语言·笔记·python·gitlab·bug
谷晓光30 分钟前
Python 中 `r` 前缀:字符串处理的“防转义利器”
开发语言·python
姚毛毛31 分钟前
Windows上,10分钟构建一个本地知识库
python·ai·rag
站大爷IP1 小时前
Python ZIP文件操作全解析:从基础压缩到高级技巧
python
纪元A梦1 小时前
华为OD机试真题——通过软盘拷贝文件(2025A卷:200分)Java/python/JavaScript/C++/C语言/GO六种最佳实现
java·javascript·c++·python·华为od·go·华为od机试题
用户867132495741 小时前
97% 的 Python 项目可以使用 partial() 更简洁
python
灏瀚星空2 小时前
从单机工具到协同平台:开源交互式模拟环境的技术演进之路
经验分享·笔记·python·开源·oneapi
西柚小萌新2 小时前
【Python爬虫实战篇】--Selenium爬取Mysteel数据
开发语言·爬虫·python