Python math.frexp 与 math.ldexp:拆开浮点数,弄清精确还原的边界

10-23 5阅读

排查浮点数时,十进制打印结果经常只能告诉我们“看起来是多少”。如果想知道一个 float 的二进制尺度、把很大或很小的数归一化,或者按 2 的整数次幂缩放,math.frexp 与 math.ldexp 更直接。本文从 6.5 开始,一直走到最小次正规数、无穷大和 NaN,并把“精确还原”能保证什么讲清楚。

Python math.frexp 与 math.ldexp:拆开浮点数,弄清精确还原的边界
模型生成的概念示意图:6.5 = 0.8125 × 2³。箭头表示拆解与重组关系,不是运行截图,也不是 IEEE 754 内存位布局。

运行范围:下文五个程序只使用标准库 math,必要时读取 sys.float_info,不读写文件、不访问网络。实际运行版本为 Linux 环境下的 CPython 3.12.14 与 CPython 3.13.5,分别执行普通模式和 -O 模式。两个解释器均使用本文检查的 binary64 参数;涉及极小数舍入的输出限定于本次实测环境。在线文档是滚动维护页面,不能把其补丁版号当作本文的测试版本。

一、frexp 返回的 m 和 e 到底表示什么

对有限、非零的浮点数 x,math.frexp(x) 返回二元组 (m, e):m 是带符号的浮点尾数,e 是整数,满足 0.5 ≤ |m| < 1,以及数学关系 x = m × 2ᵉ。这里的“尾数”指缩放后的有效数,不是十进制小数点后面的部分;e 也不是十进制位数。接口定义见 Python 官方 frexp 文档。

例如 6.5 可以写成二进制 110.1₂。把二进制点移到首个 1 之前,得到 0.1101₂,再乘以 2³。0.1101₂ 的十进制值正是 0.8125,所以结果是 (0.8125, 3)。负数只会让 m 带上负号,归一化区间看的是绝对值。

同一个数当然有多种等价写法:8 = 1 × 2³ = 0.5 × 2⁴。但 frexp 选择的区间不包含 1,因此 8.0 返回 (0.5, 4)。这个约定也解释了下面的边界:略小于 1 的浮点数对应 e = 0,恰好 1.0 则对应 e = 1。

完整程序:01_normalization.py。复制整个代码框后可以单独运行。

import math


def require(condition, label):
    if not condition:
        raise RuntimeError(label)


cases = [
    ("N01", 6.5, 0.8125, 3),
    ("N02", -6.5, -0.8125, 3),
    ("N03", 8.0, 0.5, 4),
    ("N04", 0.125, 0.5, -2),
    ("N05", math.nextafter(1.0, 0.0),
     0.9999999999999999, 0),
    ("N06", 1.0, 0.5, 1),
]
for label, x, expected_m, expected_e in cases:
    m, e = math.frexp(x)
    require((m, e) == (expected_m, expected_e), label + " pair")
    require(0.5 <= abs(m) < 1.0, label + " range")
    require(math.ldexp(m, e) == x, label + " round trip")
    print(f"{label}: x={x!r}, m={m!r}, e={e}, exact=True")
print("PASS 6 unique cases")

实际输出:

  • N01: x=6.5, m=0.8125, e=3, exact=True
  • N02: x=-6.5, m=-0.8125, e=3, exact=True
  • N03: x=8.0, m=0.5, e=4, exact=True
  • N04: x=0.125, m=0.5, e=-2, exact=True
  • N05: x=0.9999999999999999, m=0.9999999999999999, e=0, exact=True
  • N06: x=1.0, m=0.5, e=1, exact=True
  • PASS 6 unique cases

程序同时检查预先写明的 (m, e)、尾数区间和精确回程,避免只比较“拆开后又拼回来”,却漏掉尾数没有归一化的错误。这里使用 == 而非 isclose,因为测试目标就是原 float 的精确还原,不是容许误差的近似计算。

二、精确回程不会把二进制 float 变成精确十进制数

“ldexp 能还原 frexp 的结果”中的对象,是进入函数的浮点值。假如输入在转成 float 时已经发生舍入,这两个函数不会找回此前丢失的十进制信息或大整数低位。Python 的浮点数官方教程解释了二进制存储与十进制显示的区别。

下面把五种常见误解放在同一个可运行程序中:

  • 1000 的十进制写法有 4 位,但 frexp 的指数是 10,因为它按 2 的幂缩放。
  • 0.1 拆成 (0.8, -3) 后仍可准确回到同一个 float;用整数比例交叉相乘,可以确认这个 float 不等于数学上的 1/10。不要用 0.1 == 1/10 验证这一点,因为右侧除法也会产生 float。
  • 把 m 格式化为两位小数再转回来,会改变本例的值。格式化适合展示,不适合偷偷替换计算中的尾数。
  • 2⁵³ + 1 是精确的 Python 整数,但传给本次测试的 frexp 时会转成 float。还原结果对应 2⁵³,不能当作任意精度整数序列化。
  • 6.5 的 float.hex() 使用 1.a × 2² 的十六进制表达;frexp 使用 0.8125 × 2³。对这个正常数,两种有效数约定相差一个 2,所以指数差 1。不要把这个例子的关系机械套到 hex() 以 0 开头的次正规数表示上。

完整程序:02_not_decimal.py。复制整个代码框后可以单独运行。

import math
import sys


def require(condition, label):
    if not condition:
        raise RuntimeError(label)


require((sys.float_info.radix, sys.float_info.mant_dig) == (2, 53),
        "This program expects binary64 precision")

m, e = math.frexp(1000.0)
require((m, e) == (0.9765625, 10), "D01 binary exponent")
require(e != len(str(1000)), "D01 not decimal digits")
print(f"D01: 1000.0 -> ({m}, {e}); decimal_digits=4")

x = 0.1
m, e = math.frexp(x)
numerator, denominator = x.as_integer_ratio()
require((m, e) == (0.8, -3), "D02 pair")
require(math.ldexp(m, e) == x, "D02 float round trip")
require(numerator * 10 != denominator, "D02 not exactly 1/10")
print(f"D02: 0.1 -> ({m}, {e}); ratio={numerator}/{denominator}")

x = 1.23456789
m, e = math.frexp(x)
rounded_m = float(format(m, ".2f"))
rebuilt = math.ldexp(rounded_m, e)
require(rebuilt != x, "D03 rounding must change this value")
print(f"D03: m={m}, rounded_m={rounded_m}, rebuilt={rebuilt}")

n = 2**53 + 1
m, e = math.frexp(n)
rebuilt = math.ldexp(m, e)
require(rebuilt == float(n), "D04 float round trip")
require(rebuilt != n, "D04 original integer was not preserved")
print(f"D04: integer={n}, rebuilt_integer={int(rebuilt)}")

x = 6.5
m, e = math.frexp(x)
require(x.hex() == "0x1.a000000000000p+2", "D05 hex form")
require(math.ldexp(2 * m, e - 1) == x, "D05 alternate form")
require(2 * m == 1.625 and e - 1 == 2, "D05 shifted convention")
print(f"D05: hex={x.hex()}; frexp_e={e}, hex_p=2")
print("PASS 5 unique cases")

实际输出:

  • D01: 1000.0 -> (0.9765625, 10); decimal_digits=4
  • D02: 0.1 -> (0.8, -3); ratio=3602879701896397/36028797018963968
  • D03: m=0.617283945, rounded_m=0.62, rebuilt=1.24
  • D04: integer=9007199254740993, rebuilt_integer=9007199254740992
  • D05: hex=0x1.a000000000000p+2; frexp_e=3, hex_p=2
  • PASS 5 unique cases

D02 的 numerator × 10 != denominator 是整数比较,没有把“是否等于 1/10”的判断再次舍入成 float。D03 则有意演示错误处理方式:本来的尾数 0.617283945 被改成 0.62,重组后变成 1.24;这不是 ldexp 造成的精度损失。

三、零与次正规数:不要把最小正常数当成最小正数

零是归一化区间的例外,frexp(0.0) 返回 (0.0, 0)。在本文环境中,负零也会保留符号。但 0.0 == -0.0 本身为真,若算法关心这个区别,需要像下例一样用 math.copysign 检查,而不是仅比较数值相等。

sys.float_info.min 是最小正正常数,不是所有正 float 的下界。在它和零之间还有次正规数。math.ulp(0.0) 可以取得最小正次正规数。参数含义见 sys.float_info 官方说明及 math.ulp 文档。

在本次 binary64 环境中,最小正常数是 2⁻¹⁰²²,最小正次正规数是 2⁻¹⁰⁷⁴。后者的 frexp 结果是 (0.5, -1073),因为 0.5 × 2⁻¹⁰⁷³ = 2⁻¹⁰⁷⁴。不要把返回的 -1073 当成内存中的原始指数位字段,也不要据此说该数不是次正规数。frexp 返回的 m 已重新归一化,原始 x 的类别没有因此改变。

完整程序:03_zero_subnormal.py。复制整个代码框后可以单独运行。

import math
import sys


def require(condition, label):
    if not condition:
        raise RuntimeError(label)


info = sys.float_info
require((info.radix, info.mant_dig, info.min_exp, info.max_exp)
        == (2, 53, -1021, 1024), "This program expects binary64")
smallest = math.ulp(0.0)
cases = [
    ("Z01", 0.0, 0.0, 0),
    ("Z02", -0.0, -0.0, 0),
    ("Z03", info.min, 0.5, -1021),
    ("Z04", math.nextafter(info.min, 0.0),
     0.9999999999999998, -1022),
    ("Z05", smallest, 0.5, -1073),
    ("Z06", -smallest, -0.5, -1073),
]
for label, x, expected_m, expected_e in cases:
    m, e = math.frexp(x)
    y = math.ldexp(m, e)
    require((m, e) == (expected_m, expected_e), label + " pair")
    require(y == x, label + " round trip")
    require(math.copysign(1.0, m) == math.copysign(1.0, x),
            label + " mantissa sign")
    require(math.copysign(1.0, y) == math.copysign(1.0, x),
            label + " result sign")
    subnormal = 0.0 < abs(x) < info.min
    print(f"{label}: x={x.hex()}, m={m!r}, e={e}, "
          f"subnormal={subnormal}, sign_preserved=True")
print("PASS 6 unique cases")

实际输出:

  • Z01: x=0x0.0p+0, m=0.0, e=0, subnormal=False, sign_preserved=True
  • Z02: x=-0x0.0p+0, m=-0.0, e=0, subnormal=False, sign_preserved=True
  • Z03: x=0x1.0000000000000p-1022, m=0.5, e=-1021, subnormal=False, sign_preserved=True
  • Z04: x=0x0.fffffffffffffp-1022, m=0.9999999999999998, e=-1022, subnormal=True, sign_preserved=True
  • Z05: x=0x0.0000000000001p-1022, m=0.5, e=-1073, subnormal=True, sign_preserved=True
  • Z06: x=-0x0.0000000000001p-1022, m=-0.5, e=-1073, subnormal=True, sign_preserved=True
  • PASS 6 unique cases

Z03 与 Z04 分别取正常数区域的下边界及其下方的相邻 float。Z05、Z06 则检查正负最小次正规数。所有这些有限输入都能精确回程,但这不会为极小数增加有效精度;它只把已有值写成统一的形式。

四、ldexp 是二进制缩放,不是“永远无损”的承诺

math.ldexp(x, i) 的用途是按 2ⁱ 缩放 x;第一个参数不必已经位于 frexp 的归一化区间。6.5 可以直接传入,指数 2 得到 26.0;负指数则表示缩小。官方接口说明见 math.ldexp 文档。

重要区别在于:重组一个已有有限 float 的原始 (m, e),与任意改变指数来制造一个新值,不是同样的承诺。前者能还原本例输入;后者可能超出 float 范围,或者在次正规区间发生舍入,甚至归零。

另一个容易漏掉的问题是中间结果。最大有限 float 的 frexp 指数是 1024,直接调用 ldexp(m, 1024) 能还原它;先算 2.0**1024 却会溢出,即使随后再乘一个小于 1 的 m。本例专门对比这两种求值路径。文档中的数学等式不要被误读为“任意边界上都应先构造这个幂再相乘”。

完整程序:04_scaling_limits.py。复制整个代码框后可以单独运行。

import math
import sys


def require(condition, label):
    if not condition:
        raise RuntimeError(label)


info = sys.float_info
require((info.radix, info.mant_dig, info.min_exp, info.max_exp)
        == (2, 53, -1021, 1024), "This program expects binary64")
require(info.rounds == 1, "This program expects round-to-nearest")

y = math.ldexp(6.5, 2)
require(y == 26.0, "L01 unnormalized input")
print(f"L01: ldexp(6.5, 2)={y}")

y = math.ldexp(0.75, -2)
require(y == 0.1875, "L02 negative exponent")
print(f"L02: ldexp(0.75, -2)={y}")

m, e = math.frexp(info.max)
require(math.ldexp(m, e) == info.max, "L03 direct reconstruction")
try:
    m * (2.0**e)
except OverflowError:
    print(f"L03: e={e}; ldexp exact=True; separate power overflow=True")
else:
    raise RuntimeError("L03 expected power overflow")

try:
    math.ldexp(info.max, 1)
except OverflowError:
    print("L04: scaling max by two -> OverflowError")
else:
    raise RuntimeError("L04 expected result overflow")

smallest = math.ulp(0.0)
y = math.ldexp(smallest, -1)
require(y == 0.0 and math.copysign(1.0, y) == 1.0,
        "L05 half the smallest subnormal rounds to positive zero")
print(f"L05: half_smallest={y.hex()}")

y = math.ldexp(3 * smallest, -1)
require(y == 2 * smallest, "L06 midpoint rounds to even multiple")
print(f"L06: three_smallest / 2={y.hex()}")
print("PASS 6 unique cases")

实际输出:

  • L01: ldexp(6.5, 2)=26.0
  • L02: ldexp(0.75, -2)=0.1875
  • L03: e=1024; ldexp exact=True; separate power overflow=True
  • L04: scaling max by two -> OverflowError
  • L05: half_smallest=0x0.0p+0
  • L06: three_smallest / 2=0x0.0000000000002p-1022
  • PASS 6 unique cases

L03 是中间幂先溢出,而 L04 是最终结果本身过大,两者应区分。L05 中,最小正次正规数的一半无法表示,实测舍入为正零;L06 的真实值位于相邻两个可表示数的中点,实测采用偶数倍方向,得到最小次正规数的 2 倍。这两项说明随意缩小指数后不一定还能逆向还原。

这些极小数输出不是对所有平台的无条件保证。程序先核对 binary64 参数与解释器启动时记录的舍入模式;本文没有修改浮点环境。固定标签的 CPython 3.12.14 实现与 CPython 3.13.5 实现都可以核验 ldexp 的异常处理,后者还包含特定 Windows C 运行库的次正规数处理分支。本文运行的是 Linux,未声称覆盖 Windows 或其他浮点环境。

五、无穷大、NaN,以及真正会失败的防护检查

对正负无穷和 NaN,本文两个 CPython 版本的 frexp 都保留输入值并给出指数 0。这些特殊返回值不满足有限非零数的尾数区间,不能直接进入只接受正常归一化结果的算法。固定源码在 3.12.14 的 frexp 实现与 3.13.5 的 frexp 实现中显式处理了这些情况。

NaN 还需要单独判断:NaN 与自身比较也不相等,所以用 math.isnan 检查类别。下例的 classification_preserved 只表示 NaN/无穷及无穷的符号符合预期,不宣称保存 NaN 载荷、信号属性或逐位表示。

下例还验证两个不同的防护点:本次版本的 ldexp 不接受浮点指数 3.0;而 (1.0, 2) 虽然也能重建 4.0,却不是 frexp 规范化后的结果。只有回程检查而没有尾数区间检查的验证器,会错误地放行后一种输入。

完整程序:05_special_and_guard.py。复制整个代码框后可以单独运行。

import math


def require(condition, label):
    if not condition:
        raise RuntimeError(label)


def validate_normalized_pair(x, m, e):
    if not math.isfinite(x) or x == 0.0:
        raise ValueError("expected finite nonzero x")
    if not math.isfinite(m) or not 0.5 <= abs(m) < 1.0:
        raise ValueError("mantissa is not normalized")
    if type(e) is not int:
        raise TypeError("exponent must be int")
    if math.ldexp(m, e) != x:
        raise ValueError("pair does not reconstruct x")


for label, x in [("S01", math.inf), ("S02", -math.inf),
                 ("S03", math.nan)]:
    m, e = math.frexp(x)
    y = math.ldexp(m, e)
    require(e == 0, label + " exponent")
    if math.isnan(x):
        require(math.isnan(m) and math.isnan(y), label + " NaN")
        require(y != x, label + " NaN is not equal to itself")
    else:
        require(m == x and y == x, label + " infinity and sign")
    try:
        validate_normalized_pair(x, m, e)
    except ValueError:
        pass
    else:
        raise RuntimeError(label + " finite-only guard failed")
    print(f"{label}: m={m!r}, e={e}, classification_preserved=True")

try:
    math.ldexp(0.5, 3.0)
except TypeError:
    print("S04: float exponent 3.0 -> TypeError")
else:
    raise RuntimeError("S04 expected integer exponent")

validate_normalized_pair(4.0, 0.5, 3)
require(math.ldexp(1.0, 2) == 4.0, "S05 deliberately noncanonical pair")
try:
    validate_normalized_pair(4.0, 1.0, 2)
except ValueError:
    print("S05: reconstructing but unnormalized pair -> rejected")
else:
    raise RuntimeError("S05 normalization guard was bypassed")
print("PASS 5 unique cases")

实际输出:

  • S01: m=inf, e=0, classification_preserved=True
  • S02: m=-inf, e=0, classification_preserved=True
  • S03: m=nan, e=0, classification_preserved=True
  • S04: float exponent 3.0 -> TypeError
  • S05: reconstructing but unnormalized pair -> rejected
  • PASS 5 unique cases

validate_normalized_pair 是本教程为了说明不变量而写的有限非零 float 验证器,刻意拒绝零与非有限值,不是替代 math 的通用输入转换层。若业务允许这些值,应在调用它之前分类处理,而不是删除检查。

六、如何使用这组工具,以及本次验证覆盖了什么

  • 要拆解有限浮点数的尺度:使用 frexp,并同时保存完整精度的 m 与整数 e。
  • 要按 2 的整数次幂缩放:优先明确表达为 ldexp,但仍要处理最终溢出和极小结果舍入。
  • 要区分原输入类别:在归一化之前判断是否有限、是否为零;需要识别次正规数时,检查原 x,而不是检查归一化后的 m。
  • 要数十进制位数或控制显示:不要把 e 当作位数;按实际需求使用整数或字符串方法、数值格式化。
  • 要保留精确十进制含义或任意精度整数:从数据进入程序时就选择相应表示,不要指望拆解一个 float 恢复已经舍入的信息。

本次共设计 28 个不同语义用例:基本归一化 6 个、十进制与表示误区 5 个、零与次正规数 6 个、缩放边界 6 个、特殊值和防护 5 个。五个完整程序在两个解释器的普通模式与 -O 模式下运行,共 20 次程序启动、112 次用例执行;重复执行没有算成新的独立用例,四组输出逐字一致。

所有检查都使用显式 if/raise,没有依赖会被 -O 去掉的 assert。额外进行的负向控制只在内存中移除了最后一个程序的尾数区间检查:四种版本/模式组合均在 S05 报错,证明这项检查确实会捕获“能重组但不归一化”的坏输入。该负向控制不计入新增语义用例,也不改变上面展示的规范程序。

这是一组接口语义与边界行为验证,没有进行性能基准或第三方产品测试。最重要的结论是:frexp 和 ldexp 能可靠表达同一个二进制浮点值的分解与重组;它们不会扩大 float 的表示范围,也不会把已发生的十进制或整数舍入逆转回来。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。