Python数值运算与精度
Python 整数精度无限,浮点数存在精度问题,高精度场景需使用 decimal 模块。
整数精度
Python 整数无限精度
Python
# 整数无大小限制
big_number = 10**100 # 100位数字
print(big_number) # 正常输出
# 大整数运算
a = 12345678901234567890
b = 98765432109876543210
print(a + b) # 111111111011111111100
Python 3 整数自动扩展,无溢出问题。
整数运算
Python
# 基本运算
print(10 + 3) # 13
print(10 - 3) # 7
print(10 * 3) # 30
print(10 // 3) # 3(整除)
print(10 % 3) # 1(取余)
print(10 / 3) # 3.333...(浮点除法)
# 幂运算
print(2 ** 10) # 1024
浮点数精度问题
精度丢失示例
Python
# 经典问题
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
# 原因:二进制表示无法精确存储某些十进制数
比较浮点数
Python
# 错误:直接比较
if 0.1 + 0.2 == 0.3:
print("equal")
# 正确:使用容差
def approx_equal(a, b, tolerance=1e-9):
return abs(a - b) < tolerance
if approx_equal(0.1 + 0.2, 0.3):
print("equal") # 输出
显示精度控制
Python
value = 0.1 + 0.2
print(f"{value:.2f}") # 0.30(格式化显示)
print(round(value, 2)) # 0.3(四舍五入)
格式化和 round 不改变实际值,只影响显示。
decimal 模块
解决精度问题
Python
from decimal import Decimal, getcontext
# 设置精度
getcontext().prec = 28 # 28位精度
# 高精度计算
a = Decimal('0.1')
b = Decimal('0.2')
print(a + b) # 0.3(精确)
print(a + b == Decimal('0.3')) # True
Decimal 基本用法
Python
from decimal import Decimal
# 从字符串创建(推荐)
d1 = Decimal('0.1')
# 从整数创建
d2 = Decimal(10)
# 从浮点数创建(不推荐,已丢失精度)
d3 = Decimal(0.1) # 不精确
# 运算
print(Decimal('1.5') + Decimal('2.5')) # 4.0
print(Decimal('10') / Decimal('3')) # 3.333333...
实际应用场景
金融计算
Python
from decimal import Decimal
price = Decimal('19.99')
quantity = Decimal('100')
total = price * quantity
print(total) # 1999.00(精确)
# 税费计算
tax_rate = Decimal('0.08')
tax = total * tax_rate
print(tax) # 159.92
精确比较
Python
from decimal import Decimal
def compare_prices(p1, p2):
p1 = Decimal(str(p1))
p2 = Decimal(str(p2))
return p1 == p2
print(compare_prices(19.99, 19.99)) # True
其他精度相关
fractions 模块(分数)
Python
from fractions import Fraction
# 精确分数运算
f1 = Fraction(1, 3) # 1/3
f2 = Fraction(2, 3) # 2/3
print(f1 + f2) # 1(精确)
# 从浮点数转换(可能不精确)
f3 = Fraction(0.25) # 1/4
print(f3) # 1/4
math 模块
Python
import math
# 浮点数函数
print(math.sqrt(2)) # 1.41421356...
print(math.pi) # 3.14159265...
# 四舍五入
print(math.floor(3.7)) # 3(向下取整)
print(math.ceil(3.2)) # 4(向上取整)
要点总结
- Python 整数无限精度,无溢出问题
- 浮点数存在精度丢失,如 0.1 + 0.2 ≠ 0.3
- 浮点数比较应使用容差方法
- 高精度场景使用 decimal 模块
- 金融、科学计算推荐 Decimal,从字符串创建
📝 发现内容有误?点击此处直接编辑