为何在IEEE浮点精度下2x - x恒等于x?
关于浮点数等式
2x - x == x的验证 我原本以为只有当浮点数的尾数(mantissa)最后一位为0时,等式2x - x == x才成立。否则,因为2x和x的指数相差1,相减时x会丢失一位精度,结果会被向上或向下舍入。
但实际实验显示,只要x和2x都是有限值,不管随机数的尾数最后一位是不是1,这个等式始终成立。
import random import struct from collections import Counter def float_to_bits(f: float) -> int: """ Convert a double-precision floating-point number to a 64-bit integer. """ # Pack the float into 8 bytes, then unpack as an unsigned 64-bit integer return struct.unpack(">Q", struct.pack(">d", f))[0] def check_floating_point_precision(num_trials: int) -> float: true_count = 0 false_count = 0 bit_counts = Counter() for _ in range(num_trials): x = random.uniform(0, 1) if 2 * x - x == x: true_count += 1 else: false_count += 1 bits = float_to_bits(x) # Extract the last three bits of the mantissa last_three_bits = bits & 0b111 bit_counts[last_three_bits] += 1 return (bit_counts, true_count / num_trials) num_trials = 1_000_000 (bit_counts, proportion_true) = check_floating_point_precision(num_trials) print(f"The proportion of times 2x - x == x holds true: {proportion_true:.6f}") print("Distribution of last three bits (mod 8):") for bits_value in range(8): print(f"{bits_value:03b}: {bit_counts[bits_value]} occurrences")
运行结果:
The proportion of times 2x - x == x holds true: 1.000000 Distribution of last three bits (mod 8): 000: 312738 occurrences 001: 62542 occurrences 010: 125035 occurrences 011: 62219 occurrences 100: 187848 occurrences 101: 62054 occurrences 110: 125129 occurrences 111: 62435 occurrences
内容的提问来源于stack exchange,提问作者dspyz
相关产品推荐
相关产品推荐

