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

入门之道,就在其中

相关推荐
Yan-英杰3 分钟前
百度搜索和文心智能体接入DeepSeek满血版——AI搜索的新纪元
图像处理·人工智能·python·深度学习·deepseek
weixin_307779131 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
多想和从前一样5 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
小喵要摸鱼6 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python
bdawn6 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
Jackson@ML6 小时前
Python数据可视化简介
开发语言·python·数据可视化
mosquito_lover16 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt
mengyoufengyu7 小时前
算法12-贪心算法
python·算法·贪心算法
T_Y99437 小时前
pythonrsa加密与sha256加密
python