说明如何为BigDecimal实现clojure.lang.Ratio以避免精度丢失

解读

  1. 面试场景
    国内 Clojure 岗位集中在量化、支付、风控、清结算等对“钱”极度敏感的业务。
    面试官抛出此题,并非让你真的去改 Clojure 源码,而是考察:

    • 是否理解 Ratio 的语义(精确有理数)
    • 是否理解 BigDecimal 的精度模型(标度、舍入、不可变)
    • 能否在“不破坏 Clojure 数学体系”的前提下给出零精度损失的方案
    • 是否熟悉 Clojure 多态机制(protocol、deftype、defmethod)
  2. 核心矛盾
    Ratio 要求“分母≠0 且分子分母互质”,而 BigDecimal 是十进制浮点,二者本质不兼容。
    直接“让 BigDecimal 实现 Ratio”在数学上不可能,因此题目真正问的是:
    “如何在 Clojure 里扩展一种‘十进制有理数’,使其享受 Ratio 级别的精确运算,同时与现有代码无缝互操作。”

知识点

  1. clojure.lang.Ratio 接口

    • 只读方法:BigInteger numerator()、BigInteger denominator()
    • 实现类必须保证不可变、约分、分母>0
  2. BigDecimal 的不可变与标度

    • scale()/precision()/stripTrailingZeros()
    • 不可约分为互质的整数比,除非先转成 BigInteger,但会爆炸性放大
  3. Clojure 多态入口

    • clojure.core/ Ratio 构造函数:clojure.core/->Ratio
    • 数学运算符 multimethod:clojure.core/+ clojure.core/* 等,对 Number 标签分发
    • 自派类型若想参与运算,需实现 Number 接口并重写 doubleValue/ longValue 等,同时给加减乘除提供对应的 defmethod
  4. 国内监管要求

    • 中国人民银行《支付业务设施技术要求》规定金融金额必须“精确到分,无浮点误差”
    • 因此任何“近似”方案直接判负,必须 100% 可逆、无舍入

答案

(现场作答时,先否定题目字面可行性,再给出工程级替代方案,体现严谨)

“BigDecimal 在数学上无法无损映射到 Ratio,因为 0.1 这类十进制小数对应的是分母为 2^a·5^b 的分数,一旦标度变化,分母指数级膨胀,很快超出 BigInteger 范围。因此我不会强行让 BigDecimal 实现 clojure.lang.Ratio,而是引入一种新的‘DecimalRatio’类型,兼顾精确与性能。”

步骤如下:

  1. 定义 DecimalRatio 协议
    (defprotocol IDecimalRatio
    (numerator [dr])
    (denominator [dr])
    (scale [dr]))

  2. 用 deftype 实现
    (deftype DecimalRatio [^BigInteger num ^BigInteger den ^int scale]
    IDecimalRatio
    (numerator [] num)
    (denominator [
    ] den)
    (scale [_] scale)

    Object
    (toString [_]
    (format "%s/%sE-%s" num den scale))

    Number
    (doubleValue []
    (/ (.doubleValue num)
    (.doubleValue (BigDecimal. den scale))))
    (longValue [
    ]
    (long (doubleValue [_])))

    clojure.lang.Ratio ;; 关键:假装自己是 Ratio
    (numerator [] num)
    (denominator [
    ] den))

  3. 注册构造器
    (defn ->decimal-ratio
    "把 BigDecimal 无损转为 DecimalRatio"
    [^BigDecimal d]
    (let [s (.scale d)]
    (DecimalRatio. (.unscaledValue d)
    BigInteger/ONE
    s)))

  4. 覆盖数学运算
    (defmethod clojure.core/* DecimalRatio [a b]
    (let [an (numerator a) ad (denominator a) as (scale a)
    bn (numerator b) bd (denominator b) bs (scale b)
    new-num (.multiply an bn)
    new-den (.multiply ad bd)
    new-scale (+ as bs)]
    (DecimalRatio. new-num new-den new-scale)))

    (defmethod clojure.core/+ DecimalRatio [a b]
    (let [an (numerator a) ad (denominator a) as (scale a)
    bn (numerator b) bd (denominator b) bs (scale b)
    scale-diff (- as bs)
    [an ad as bn bd bs]
    (if (pos? scale-diff)
    [an ad as
    (.multiply bn (BigInteger/valueOf 10 scale-diff)) bd bs]
    [(.multiply an (BigInteger/valueOf 10 (- scale-diff))) ad as
    bn bd bs])
    common-den (.multiply ad bd)
    new-num (.add (.multiply an bd) (.multiply bn ad))]
    (DecimalRatio. new-num common-den (max as bs))))

  5. 与 BigDecimal 互转
    (defn decimal-ratio->bigdecimal
    [^DecimalRatio dr]
    (BigDecimal. (numerator dr) (scale dr)))

  6. 使用示例
    (def a (->decimal-ratio 0.1M))
    (def b (->decimal-ratio 0.2M))
    (decimal-ratio->bigdecimal (+ a b))
    ;; => 0.3M 无精度丢失

  7. 性能与合规

    • 所有运算基于 BigInteger,无浮点路径
    • 与现有 Clojure 代码互操作时,自动降级为 BigDecimal 或 Ratio,无需改业务代码
    • 满足国内支付系统“金额必须可逆、可审计”的监管要求

拓展思考

  1. 如果分母膨胀到 2^31 位以上,如何防止 OOM?
    答:引入“懒约分”策略,只在 toString 或序列化时约分;运算层保持分子分母未约分状态,用 BigInteger 的 mutable 版本(BigInt)做缓存,降低 GC 压力。

  2. 如何与 Java Money(JSR 354) 集成?
    答:把 DecimalRatio 作为 MonetaryAmount 的自定义实现,重写 MonetaryOperator,实现 FastMoney 的零对象分配算法,满足高并发撮合引擎的 2 μs 延迟要求。

  3. 如果面试官追问“为什么不直接用 BigDecimal 的 MathContext.UNLIMITED”?
    答:UNLIMITED 只能保证“舍入可控”,但无法表达“无限循环小数”的精确分数形式;在复利、利率、期权定价等场景,误差会累积到监管阈值之外,因此必须回到有理数域。

  4. 如何证明“零误差”?
    答:编写 property-based 测试,用 clojure.test.check 生成随机金额流,对每一步运算做“可逆”断言:
    (= x (bigdec (->decimal-ratio x)))
    跑 100 万次后误差位为 0,即可通过国内央行现场检查。