Skip to content

数字:整数、浮点、精度与 Decimal ​

整数:任意精度 ​

Python 3 的整数(int)没有大小限制,可以表示任意大的整数:

python
>>> big = 2 ** 1000
>>> print(big)
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
>>> type(big)
<class 'int'>
>>> big + 1
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069377

对比:许多语言的整数有固定大小(32位或64位),超出范围会溢出。Python 自动扩展整数存储空间。

整数运算 ​

python
>>> 7 + 3
10
>>> 7 - 3
4
>>> 7 * 3
21
>>> 7 ** 3  # 幂运算
343

除法:/ vs // ​

/ 总是返回浮点数:

python
>>> 10 / 3
3.3333333333333335
>>> 10 / 2
5.0  # 即使整除,也返回 float

// 是地板除(floor division),向下取整,返回整数:

python
>>> 10 // 3
3
>>> -10 // 3
-4  # 向负无穷方向取整
>>> 10.0 // 3
3.0  # 操作数有浮点数时,返回 float

取模 ​

% 返回除法余数:

python
>>> 10 % 3
1
>>> -10 % 3
2  # 结果符号与除数相同

验证关系:a == (a // b) * b + (a % b)

python
>>> a, b = 10, 3
>>> (a // b) * b + (a % b) == a
True

divmod():同时获取商和余数 ​

python
>>> divmod(10, 3)
(3, 1)
>>> quotient, remainder = divmod(10, 3)
>>> quotient
3
>>> remainder
1

浮点数:IEEE 754 双精度 ​

Python 的 float 使用 IEEE 754 双精度(64位)表示,精度约 15-17 位十进制数字。

浮点精度陷阱 ​

经典问题:

python
>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1 + 0.2 == 0.3
False

原因:多数十进制小数无法精确表示为二进制浮点数。0.1 在二进制中是无限循环小数,存储时被截断。

查看实际存储值:

python
>>> from decimal import Decimal
>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')

比较浮点数 ​

不要用 == 直接比较浮点数,使用容差:

python
>>> a = 0.1 + 0.2
>>> b = 0.3
>>> abs(a - b) < 1e-9  # 容差 10^-9
True

标准库提供 math.isclose():

python
>>> import math
>>> math.isclose(0.1 + 0.2, 0.3)
True
>>> math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-9, abs_tol=0.0)
True

参数:

  • rel_tol:相对容差(默认 1e-9)
  • abs_tol:绝对容差(默认 0.0)

浮点数的特殊值 ​

python
>>> float('inf')   # 正无穷
inf
>>> float('-inf')  # 负无穷
-inf
>>> float('nan')   # Not a Number
nan
>>> math.isinf(float('inf'))
True
>>> math.isnan(float('nan'))
True

nan 不等于任何值,包括自己:

python
>>> nan = float('nan')
>>> nan == nan
False
>>> math.isnan(nan)
True

Decimal:精确小数 ​

金融计算、货币、需要精确小数的场景,使用 decimal.Decimal:

python
>>> from decimal import Decimal
>>> Decimal('0.1') + Decimal('0.2')
Decimal('0.3')
>>> Decimal('0.1') + Decimal('0.2') == Decimal('0.3')
True

注意:用字符串初始化 Decimal,不用浮点数:

python
>>> Decimal(0.1)  # 错误:继承了 float 的精度问题
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal('0.1')  # 正确:精确表示
Decimal('0.1')

设置精度 ​

python
>>> from decimal import Decimal, getcontext
>>> getcontext().prec = 6  # 设置为 6 位有效数字
>>> Decimal('1') / Decimal('7')
Decimal('0.142857')
>>> getcontext().prec = 28  # 恢复默认 28 位
>>> Decimal('1') / Decimal('7')
Decimal('0.1428571428571428571428571429')

Decimal 运算 ​

python
>>> price = Decimal('19.99')
>>> tax_rate = Decimal('0.08')
>>> tax = price * tax_rate
>>> total = price + tax
>>> print(total)
21.5892
>>> total.quantize(Decimal('0.01'))  # 四舍五入到分
Decimal('21.59')

复数 ​

Python 内置复数支持,虚部用 j 或 J 表示:

python
>>> z = 3 + 4j
>>> type(z)
<class 'complex'>
>>> z.real
3.0
>>> z.imag
4.0
>>> abs(z)  # 模
5.0
>>> z * z
(-7+24j)

数字类型转换 ​

python
>>> int(3.14)
3
>>> int(3.99)  # 截断,不是四舍五入
3
>>> float(10)
10.0
>>> round(3.14159, 2)  # 四舍五入到 2 位小数
3.14
>>> round(2.5)  # 银行家舍入:偶数舍入
2
>>> round(3.5)
4

round() 的"奇偶舍入"规则:当处于中间值时,舍入到最近的偶数。

数学函数 ​

python
>>> import math
>>> math.sqrt(16)
4.0
>>> math.pow(2, 10)
1024.0
>>> math.floor(3.7)  # 向下取整
3
>>> math.ceil(3.2)   # 向上取整
4
>>> math.trunc(3.7)  # 截断小数部分
3
>>> math.log(100, 10)  # 以 10 为底的对数
2.0
>>> math.sin(math.pi / 2)
1.0

数字字面量格式 ​

提高可读性:

python
>>> 1_000_000  # 下划线分隔,不影响值
1000000
>>> 0b1010  # 二进制
10
>>> 0o12    # 八进制
10
>>> 0xA     # 十六进制
10

练习 ​

  1. 大整数计算:计算 2 ** 10000 有多少位数字(提示:转换为字符串后取长度)。

  2. 浮点精度:验证以下表达式,并解释结果:

    python
    (0.1 + 0.1 + 0.1) == 0.3
    sum([0.1] * 10) == 1.0
  3. 地板除与取模:给定秒数(如 7385),计算小时、分钟、秒。

    python
    seconds = 7385
    hours = seconds // 3600
    remainder = seconds % 3600
    minutes = remainder // 60
    secs = remainder % 60
    print(f"{hours}小时 {minutes}分 {secs}秒")
  4. 货币计算:用 Decimal 计算购物车:商品价格 [19.99, 5.50, 12.30],税率 8.5%,总价四舍五入到分。

  5. 复数运算:计算 (1+2j) * (3-4j) 并验证结果。

  6. 数字验证:编写函数判断一个字符串是否可以转换为整数、浮点数或 Decimal。

完成练习后,打开本章答案页核对。

本章小结 ​

第一章建立了 Python 的基础:

  • 运行环境与交互式解释器
  • 值、对象、名字绑定的关系
  • 控制流:if、while、for、break、continue
  • 运算符:布尔逻辑、短路求值、比较链
  • 数字类型:int 任意精度、float 精度限制、Decimal 精确计算

这些概念是后续所有章节的基础。第二章将学习函数、作用域与闭包。

回到第一章概览 · 返回Python 学习路线

用心记录每一步成长