从零开始的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

入门之道,就在其中

相关推荐
meilindehuzi_a7 分钟前
Python 基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
Zane199420 分钟前
调用了 async 函数却没执行?一文讲透协程、event loop 与 await
后端·python
OPEN-F24 分钟前
Python进阶教程:装饰器与生成器深入
开发语言·python
zhipujiaoyu29 分钟前
2026年大数据专科何去何从?就业前景、发展趋势全揭秘!
大数据·python
l1258651 小时前
# RAG噪声知识库治理:一致性与可信度的四层防线设计
数据库·人工智能·python·自然语言处理·langchain
zoujiahui_20181 小时前
别再只写 np.random.seed() 了:default_rng 与 np.random、random 到底差在哪?
python
Patrick在香港1 小时前
Claude Agent 进阶:4 种工具调用编排模式,让 0820 那 13 个 endpoint 并行起来
python·ai·ai编程
qq_513728042 小时前
StaleElementReferenceException(陈旧元素引用异常)
python
千里码aicood2 小时前
基于Python的电商数据采集系统(大数据+爬虫)
开发语言·python
战略性的菠萝2 小时前
研究生基础-Python快速入门(终)——面向对象
python