"""Offline Computer Organization lab for Chapter 05 (floating-point-ieee754)."""
from decimal import Decimal
import json
import math
import struct
VERSION = "CPython 3.12.14 offline computer organization simulation verifier"
def decode_float32(num: float) -> dict:
packed = struct.pack("!f", num)
bits = "".join(f"{b:08b}" for b in packed)
s, e, m = bits[0], bits[1:9], bits[9:]
exp_stored = int(e, 2)
exp_actual = exp_stored - 127
reconstructed = struct.unpack("!f", packed)[0]
return {
"sign": s,
"exponent": e,
"mantissa": m,
"exp_stored": exp_stored,
"exp_actual": exp_actual,
"reconstructed_str": f"{reconstructed:.17g}",
}
def case_ieee754_float32_decompose():
r_half = decode_float32(0.5)
r_neg_half = decode_float32(-0.5)
r_01 = decode_float32(0.1)
r_pi = decode_float32(3.14)
actual = {
"0.5": (r_half["sign"], r_half["exp_stored"], r_half["exp_actual"], r_half["mantissa"]),
"-0.5": (r_neg_half["sign"], r_neg_half["exp_stored"], r_neg_half["exp_actual"], r_neg_half["mantissa"]),
"0.1": (r_01["sign"], r_01["exp_stored"], r_01["exp_actual"], r_01["mantissa"]),
"3.14": (r_pi["sign"], r_pi["exp_stored"], r_pi["exp_actual"], r_pi["mantissa"]),
"0.1_exact_f32": str(Decimal(struct.unpack("!f", struct.pack("!f", 0.1))[0])),
}
expected = {
"0.5": ("0", 126, -1, "00000000000000000000000"),
"-0.5": ("1", 126, -1, "00000000000000000000000"),
"0.1": ("0", 123, -4, "10011001100110011001101"),
"3.14": ("0", 128, 1, "10010001111010111000011"),
"0.1_exact_f32": "0.100000001490116119384765625",
}
return {
"name": "ieee754_float32_decompose",
"summary": "用 struct.pack('!f') 真实拆解 0.5、-0.5、0.1 与 3.14 的 IEEE 754 单精度符号/阶码/尾数位模式",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_point1_plus_point2_and_decimal():
f_eq = (0.1 + 0.2) == 0.3
dec_sum = Decimal("0.1") + Decimal("0.2")
cents_sum = 10 + 20
eps_eq = abs((0.1 + 0.2) - 0.3) < 1e-9
actual = {
"float_0.1_plus_0.2_eq_0.3": f_eq,
"float_sum_repr": repr(0.1 + 0.2),
"decimal_sum": str(dec_sum),
"decimal_eq_0.3": dec_sum == Decimal("0.3"),
"cents_sum": cents_sum,
"epsilon_equal": eps_eq,
}
expected = {
"float_0.1_plus_0.2_eq_0.3": False,
"float_sum_repr": "0.30000000000000004",
"decimal_sum": "0.3",
"decimal_eq_0.3": True,
"cents_sum": 30,
"epsilon_equal": True,
}
return {
"name": "point1_plus_point2_and_decimal",
"summary": "实测 0.1+0.2 != 0.3 的二进制舍入误差,并验证 Decimal、整数分及容差比较三种正确实践",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_precision_loss_three_cases():
# Case 1: powers of 2 fractions exact vs 0.1 inexact
exact_pow2 = all(Decimal(x) == Decimal(str(x)) for x in (0.5, 0.25, 0.125))
# Case 2: large + small in float32: 16777216.0 + 1.0 == 16777216.0
f32_big = struct.unpack("!f", struct.pack("!f", 16777216.0))[0]
f32_big_plus_1 = struct.unpack("!f", struct.pack("!f", f32_big + 1.0))[0]
f32_big_plus_2 = struct.unpack("!f", struct.pack("!f", f32_big + 2.0))[0]
# Case 3: catastrophic cancellation in float32
a32 = struct.unpack("!f", struct.pack("!f", 1.2345678))[0]
b32 = struct.unpack("!f", struct.pack("!f", 1.2345677))[0]
diff32 = struct.unpack("!f", struct.pack("!f", a32 - b32))[0]
actual = {
"pow2_fractions_exact": exact_pow2,
"f32_2pow24_plus_1_swallowed": f32_big_plus_1 == f32_big,
"f32_2pow24_plus_2_ulp": f32_big_plus_2 - f32_big,
"f32_catastrophic_diff_not_1e_7": diff32 != 1e-7,
}
expected = {
"pow2_fractions_exact": True,
"f32_2pow24_plus_1_swallowed": True,
"f32_2pow24_plus_2_ulp": 2.0,
"f32_catastrophic_diff_not_1e_7": True,
}
return {
"name": "precision_loss_three_cases",
"summary": "验证浮点数三类精度损失:二进制转换误差、float32 中 2^24+1 被吞没(ULP=2.0)及相近数相减误差",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_special_values_and_formats():
pos_zero = decode_float32(0.0)
neg_zero = decode_float32(-0.0)
pos_inf = decode_float32(float("inf"))
neg_inf = decode_float32(float("-inf"))
nan_val = decode_float32(float("nan"))
# smallest positive subnormal float32: bit pattern 0x00000001
subnormal = struct.unpack("!f", struct.pack("!I", 1))[0]
sub_bits = decode_float32(subnormal)
actual = {
"pos_zero": (pos_zero["sign"], pos_zero["exp_stored"], pos_zero["mantissa"] == "0" * 23),
"neg_zero": (neg_zero["sign"], neg_zero["exp_stored"], neg_zero["mantissa"] == "0" * 23),
"pos_inf": (pos_inf["sign"], pos_inf["exp_stored"], pos_inf["mantissa"] == "0" * 23),
"neg_inf": (neg_inf["sign"], neg_inf["exp_stored"], neg_inf["mantissa"] == "0" * 23),
"nan": (nan_val["exp_stored"], nan_val["mantissa"] != "0" * 23, float("nan") == float("nan"), math.isnan(float("nan"))),
"subnormal": (sub_bits["exp_stored"], sub_bits["mantissa"] != "0" * 23, subnormal > 0.0),
"double_spec": {"exp_bits": 11, "bias": 1023, "mantissa_bits": 52, "total_bits": 1 + 11 + 52},
}
expected = {
"pos_zero": ("0", 0, True),
"neg_zero": ("1", 0, True),
"pos_inf": ("0", 255, True),
"neg_inf": ("1", 255, True),
"nan": (255, True, False, True),
"subnormal": (0, True, True),
"double_spec": {"exp_bits": 11, "bias": 1023, "mantissa_bits": 52, "total_bits": 64},
}
return {
"name": "special_values_and_formats",
"summary": "验证 IEEE 754 零(±0)、非归一化数、±Infinity 与 NaN 的指数/尾数位模式及双精度位宽配置",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_ieee754_float32_decompose(),
case_point1_plus_point2_and_decimal(),
case_precision_loss_three_cases(),
case_special_values_and_formats(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。
入口文件:projects/computer-organization-floating-point-ieee754-lab/explore-floating-point-ieee754.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-floating-point-ieee754.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2626.zip
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a2616.zip