chronaxis.core.quantile_reference
源码基线:8904c2f744951857659abd40aaa3535d57faf53c
1"""在标量原dtype域排序并对唯一一对相邻样本作精确加权插值。"""23from fractions import Fraction4from itertools import chain5from .numeric import _exact_float6from .types import QualityFlag as Q789def ordered_reference(chunks, index, remainder, denominator):10 """在全部已选标量中定位顺序统计值,再计算线性插值。1112 参数: chunks为不重叠的已选原值块;index为下秩,余数/分母给出上秩权重。13 返回: (数值或None,质量),精确秩保持原dtype。14 异常: 排序需要的内存由调用方预付,分配错误直接传播。15 """16 ordered = None17 try:18 # 仅精确秩才直接返回整数;其他情况先证明两个端点能精确进入浮点域。19 ordered = sorted(chain.from_iterable(chunks))20 lo = ordered[index]21 if not remainder:22 return lo, Q.NONE23 hi = ordered[index + 1]24 left, qa = _exact_float(lo)25 right, qb = _exact_float(hi)26 if qa or qb:27 return None, qa | qb28 # 两个有限端点的凸组合仍在其范围内,使用精确分数避免异号差溢出及消去。29 exact = (Fraction(left) * (denominator - remainder) + Fraction(right) * remainder) / denominator30 value = float(exact)31 if (value == 0 and exact) or (type(lo) is int and exact.denominator == 1 and int(value) != exact):32 return None, Q.PRECISION_LOSS33 return value, Q.NONE34 finally:35 # 费用由外层释放;本层回溯只保留错误位置,不继续占用排序副本。36 # chunks 是借用输入,只断开本层参数,不修改或清空调用者的数据。37 chunks = ordered = None38