python——数学模块(math模块)(1)

简介: python——数学模块(math模块)(1)

我们来看一下 Python 中数学相关模块,如下所示:图片.png

本文具体介绍一下相对比较常用的模块:math、decimal 和 random。

math 模块


先来看一下 math 模块中包含内容,如下所示:

>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

接下来具体看一下该模块的常用函数和常量。

ceil(x)

返回 x 的上限,即大于或者等于 x 的最小整数。看下示例:

import math
x = -1.5
print(math.ceil(x))

floor(x)

返回 x 的向下取整,小于或等于 x 的最大整数。看下示例:

import math
x = -1.5
print(math.floor(x))

fabs(x)

返回 x 的绝对值。看下示例:

import math
x = -1.5
print(math.fabs(x))

fmod(x, y)

返回 x/y 的余数,值为浮点数。看下示例:

import math
x = 3
y = 2
print(math.fmod(x, y))

factorial(x)

返回 x 的阶乘,如果 x 不是整数或为负数时则将引发 ValueError。看下示例:

import math
x = 3
print(math.factorial(3))


相关文章
|
1天前
|
Python Windows
python中的异常与模块
python中的异常与模块
8 1
|
10天前
|
JSON 数据格式 Python
Python标准库中包含了json模块,可以帮助你轻松处理JSON数据
【4月更文挑战第30天】Python的json模块简化了JSON数据与Python对象之间的转换。使用`json.dumps()`可将字典转为JSON字符串,如`{"name": "John", "age": 30, "city": "New York"}`,而`json.loads()`则能将JSON字符串转回字典。通过`json.load()`从文件读取JSON数据,`json.dump()`则用于将数据写入文件。
16 1
|
11天前
|
Python
Python实现压缩解压---tarfile模块详解
Python实现压缩解压---tarfile模块详解
|
11天前
|
Linux Python Windows
Python中time和datetime模块详解
Python中time和datetime模块详解
|
12天前
|
存储 Linux 数据安全/隐私保护
python的压缩模块zipfile详解
python的压缩模块zipfile详解
|
12天前
|
Linux Python Windows
python的os模块详细解读(二)
python的os模块详细解读(二)
|
12天前
|
移动开发 Linux Shell
python的os模块详细解读(一)
python的os模块详细解读(一)
python的os模块详细解读(一)
|
12天前
|
Python 容器
python内置函数、数学模块、随机模块(二)
python内置函数、数学模块、随机模块(二)
|
12天前
|
索引 Python
python内置函数、数学模块、随机模块(一)
python内置函数、数学模块、随机模块(一)
|
12天前
|
容器
【Python21天学习挑战赛】-迭代器 & f-格式化 & 模块
【Python21天学习挑战赛】-迭代器 & f-格式化 & 模块