返回题库

代码 Python Decimal 与 Float

Code Python Decimal Vs Float

专题
Algorithmic Programming / 算法编程
难度
L1
来源
MyntBit

题目详情

高频交易系统每日处理百万笔货币交易。精度至关重要,避免小误差累积导致重大财务损失。考虑 Python 实现处理这些货币计算。

任务:比较 Python float 和 Decimal 类型在货币计算中的差异。float 使用 IEEE 754 双精度,0.1 无法精确表示 → 累积误差。Decimal 使用十进制精确表示 → 无累积误差。演示:sum([0.1] * 10) 用 float = 0.9999999999999999,用 Decimal = 1.0。高频交易必须使用 Decimal。

英文原题

A high-frequency trading system processes millions of currency transactions daily. Accuracy is paramount to avoid accumulating small errors that could lead to significant financial losses. Consider a Python implementation for handling these currency calculations. Why might a trading system choose to use Python's decimal.Decimal data type instead of the built-in float data type for representing currency values?

解析

问题分析

A high-frequency trading system processes millions of currency transactions daily. Accuracy is paramount to avoid accumulating small errors that could lead to significant financial losses. Consider a Python implementation for handling these currency calculations. Why might a trading system choose to

解法

根据题目要求实现相应功能。核心逻辑需要:

// 核心数据结构和方法——根据题目 API 约定实现
// 1. 确定状态表示——选择支持所需操作的数据结构
// 2. 实现核心算法——确保 O(·) 时间复杂度和正确性
// 3. 处理边界条件——空输入、极值参数、并发访问

验证

用具体输入验证:构造已知输入的测试用例,确认输出匹配预期结果。

复杂度与边界

  • 时间复杂度:取决于选用的算法
  • 空间复杂度:取决于数据规模
  • 关键边界条件:空输入、极值参数、并发场景下的正确性保证

英文解析

Analysis

A high-frequency trading system processes millions of currency transactions daily. Accuracy is paramount to avoid accumulating small errors that could lead to significant financial losses. Python's float type uses IEEE 754 binary floating-point, unable to exactly represent decimal fractions like 0.1 or 0.01 - these values are stored as approximations, causing roundoff errors that accumulate over millions of operations. Python's Decimal type uses base-10 arithmetic, providing exact decimal representation and eliminating roundoff accumulation.

Solution

from decimal import Decimal, getcontext

def compute_total_decimal(prices, quantities):
    ctx = getcontext()
    ctx.prec = 28  # 28 decimal places for financial precision
    total = Decimal('0')
    for price, qty in zip(prices, quantities):
        total += Decimal(str(price)) * Decimal(str(qty))
    return float(total)  # Convert back for display

# float version - accumulates errors
def compute_total_float(prices, quantities):
    total = 0.0
    for price, qty in zip(prices, quantities):
        total += price * qty
    return total

# Example: 1M transactions at $0.01 each
# float: total = 10000.0000001 (error accumulates)
# Decimal: total = 10000.00 (exact)

Complexity & Edge Cases

  • Time complexity: O(N) for both versions
  • Space complexity: O(1)
  • Edge cases: (1) Float accumulates error proportional to operation count (2) Decimal is slower due to base-10 arithmetic (3) Context precision must to match required decimal places (4) Converting Decimal back to float loses precision

Verification

Compute 1M additions of 0.01 using both methods. Float should show accumulated error (~1e-7). Decimal should be exact. Benchmark timing: Decimal is ~10x slower but numerically correct.

Key Considerations

Decimal is essential for any financial calculation where accuracy matters. In HFT systems, accumulated float errors across millions of operations can cause significant PnL discrepancies. The 10x performance penalty of Decimal is acceptable when the alternative is systematic financial error. Always use Decimal for pricing, PnL, and settlement calculations in trading systems.