跳转到主要内容
模块 4 · 第 3 课(共 4)课程中的15/36~10 min
模块课程(3/4)

数字和数学模块

Python 区分两种基本数字类型: int (任意精度 整数 — 无溢出)和 float (64 位浮点、双精度 精度)。

Python
type(42)       # <class 'int'>
type(3.14)     # <class 'float'>
type(10 ** 100)  # <class 'int'>   — interi grandi a piacere

算术运算符

| 欧普 | 意义 | 示例 | 结果 | | ---- | ------------- | --------- | ---------------- | ------ | | + | +加法 | 2 + 3 | 5 | | - | 减法 | 5 - 2 | 3 | | * | 产品 | 4 * 3 | 12 | | / | 真实划分 | 10 / 4 | 10 / 4 2.5 | | // | 整数 除 | 10 // 4 | 10 // 4 2 | | % | %模(余数) | 10 % 3 | 1 | 1 | | ** | **电源 | 2 ** 10 | 2 ** 10 1024 | 1024 |

警告:/ 始终返回 float,即使有两个整数 (10 / 2 返回 5.0,而不是 5)。对于整数除法,请使用 //。

Python
10 / 4    # 2.5
10 // 4   # 2
-7 // 2   # -4   (arrotonda verso il basso, non verso lo zero)

数字内置

Python
abs(-5)               # 5
min(3, 1, 2)          # 1
max([3, 1, 2])        # 3   (su iterabile)
round(3.7)            # 4
round(3.14159, 2)     # 3.14
sum([1, 2, 3])        # 6

math 模块

Python
import math
math.pi               # 3.141592653589793
math.sqrt(16)         # 4.0
math.floor(3.9)       # 3   (verso meno infinito)
math.ceil(3.1)        # 4   (verso più infinito)
math.log(math.e)      # 1.0
math.gcd(12, 18)      # 6

浮动陷阱

浮点数是二进制近似值:0.1 + 0.2 不完全等于 0.3。

Python
0.1 + 0.2           # 0.30000000000000004
0.1 + 0.2 == 0.3    # False !

为了安全比较,请使用 math.isclose(a, b) ,或者在金融环境中,使用 decimal 模块。

浮点精度和小数模块

Python 中的浮点数被实现为双精度浮点数(IEEE 754 标准)。因此,像 0.1 + 0.2 这样的计算不会准确地产生 0.3,而是产生 0.30000000000000004。如果您需要绝对的数学精度(例如对于金融应用程序),请使用标准库的 decimal 模块。

尝试一下

锻炼#python.m4.l3.e1
尝试:0加载中...

给定“秒 = 3725”,使用 // 和 % 计算“小时”、“分钟”、“剩余秒数”。评估元组“(小时,分钟,剩余秒)”。

正在加载编辑器...
显示提示

// 进行整数除法,% 余数。

3 次尝试后可用的解决方案

复习练习

锻炼#python.m4.l3.e2
尝试:0加载中...

给定“radius = 5”,使用 math.pi 计算“area”中的圆面积。使用 round 计算四舍五入到小数点后 2 位的“面积”。

正在加载编辑器...
显示提示

math.pi * 半径 ** 2

3 次尝试后可用的解决方案

额外的挑战

锻炼#python.m4.l3.e3
尝试:0加载中...

Import the `math` module. Calculate the square root of `16` using `math.sqrt`, add the result to the rounded value of `3.74` (using `round()`), and store the final sum in `total_val`. Finally, evaluate the variable.

正在加载编辑器...
显示提示

math.sqrt(16) 返回 4.0。 round(3.74) 返回 4。将它们相加并分配给total_val。

3 次尝试后可用的解决方案