数字:整数、浮点、精度与 Decimal
整数:任意精度
Python 3 的整数(int)没有大小限制,可以表示任意大的整数:
>>> big = 2 ** 1000
>>> print(big)
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
>>> type(big)
<class 'int'>
>>> big + 1
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069377对比:许多语言的整数有固定大小(32位或64位),超出范围会溢出。Python 自动扩展整数存储空间。
整数运算
>>> 7 + 3
10
>>> 7 - 3
4
>>> 7 * 3
21
>>> 7 ** 3 # 幂运算
343除法:/ vs //
/ 总是返回浮点数:
>>> 10 / 3
3.3333333333333335
>>> 10 / 2
5.0 # 即使整除,也返回 float// 是地板除(floor division),向下取整,返回整数:
>>> 10 // 3
3
>>> -10 // 3
-4 # 向负无穷方向取整
>>> 10.0 // 3
3.0 # 操作数有浮点数时,返回 float取模
% 返回除法余数:
>>> 10 % 3
1
>>> -10 % 3
2 # 结果符号与除数相同验证关系:a == (a // b) * b + (a % b)
>>> a, b = 10, 3
>>> (a // b) * b + (a % b) == a
Truedivmod():同时获取商和余数
>>> divmod(10, 3)
(3, 1)
>>> quotient, remainder = divmod(10, 3)
>>> quotient
3
>>> remainder
1浮点数:IEEE 754 双精度
Python 的 float 使用 IEEE 754 双精度(64位)表示,精度约 15-17 位十进制数字。
浮点精度陷阱
经典问题:
>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1 + 0.2 == 0.3
False原因:多数十进制小数无法精确表示为二进制浮点数。0.1 在二进制中是无限循环小数,存储时被截断。
查看实际存储值:
>>> from decimal import Decimal
>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')比较浮点数
不要用 == 直接比较浮点数,使用容差:
>>> a = 0.1 + 0.2
>>> b = 0.3
>>> abs(a - b) < 1e-9 # 容差 10^-9
True标准库提供 math.isclose():
>>> 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)
浮点数的特殊值
>>> float('inf') # 正无穷
inf
>>> float('-inf') # 负无穷
-inf
>>> float('nan') # Not a Number
nan
>>> math.isinf(float('inf'))
True
>>> math.isnan(float('nan'))
Truenan 不等于任何值,包括自己:
>>> nan = float('nan')
>>> nan == nan
False
>>> math.isnan(nan)
TrueDecimal:精确小数
金融计算、货币、需要精确小数的场景,使用 decimal.Decimal:
>>> from decimal import Decimal
>>> Decimal('0.1') + Decimal('0.2')
Decimal('0.3')
>>> Decimal('0.1') + Decimal('0.2') == Decimal('0.3')
True注意:用字符串初始化 Decimal,不用浮点数:
>>> Decimal(0.1) # 错误:继承了 float 的精度问题
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal('0.1') # 正确:精确表示
Decimal('0.1')设置精度
>>> 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 运算
>>> 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 表示:
>>> z = 3 + 4j
>>> type(z)
<class 'complex'>
>>> z.real
3.0
>>> z.imag
4.0
>>> abs(z) # 模
5.0
>>> z * z
(-7+24j)数字类型转换
>>> 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)
4round() 的"奇偶舍入"规则:当处于中间值时,舍入到最近的偶数。
数学函数
>>> 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数字字面量格式
提高可读性:
>>> 1_000_000 # 下划线分隔,不影响值
1000000
>>> 0b1010 # 二进制
10
>>> 0o12 # 八进制
10
>>> 0xA # 十六进制
10练习
大整数计算:计算
2 ** 10000有多少位数字(提示:转换为字符串后取长度)。浮点精度:验证以下表达式,并解释结果:
python(0.1 + 0.1 + 0.1) == 0.3 sum([0.1] * 10) == 1.0地板除与取模:给定秒数(如 7385),计算小时、分钟、秒。
pythonseconds = 7385 hours = seconds // 3600 remainder = seconds % 3600 minutes = remainder // 60 secs = remainder % 60 print(f"{hours}小时 {minutes}分 {secs}秒")货币计算:用
Decimal计算购物车:商品价格 [19.99, 5.50, 12.30],税率 8.5%,总价四舍五入到分。复数运算:计算
(1+2j) * (3-4j)并验证结果。数字验证:编写函数判断一个字符串是否可以转换为整数、浮点数或 Decimal。
完成练习后,打开本章答案页核对。
本章小结
第一章建立了 Python 的基础:
- 运行环境与交互式解释器
- 值、对象、名字绑定的关系
- 控制流:if、while、for、break、continue
- 运算符:布尔逻辑、短路求值、比较链
- 数字类型:int 任意精度、float 精度限制、Decimal 精确计算
这些概念是后续所有章节的基础。第二章将学习函数、作用域与闭包。
回到第一章概览 · 返回Python 学习路线