dymokomi/luce-std
Source of release 0.7.4
0.7.4 / tests / math_accuracy / generate_vectors.py
#!/usr/bin/env python3
"""Write vectors.lucb beside this file: log1p/expm1 against Decimal references, never the host libm.
Inputs are represented exactly before decimal evaluation. Recompute each reference
at two precisions and require the same binary result before using it as a vector.
The two-ulp limit is a gate for these vectors, not a proof over the whole domain.
"""
from decimal import Decimal, localcontext
from pathlib import Path
import struct
def encode(value, width):
return int.from_bytes(struct.pack(">f" if width == 32 else ">d", value), "big")
def rounded_input(value, width):
return struct.unpack(">f" if width == 32 else ">d",
struct.pack(">f" if width == 32 else ">d", value))[0]
def reference(operation, value, width, precision):
with localcontext() as context:
context.prec = precision
exact = Decimal.from_float(value)
answer = (Decimal(1) + exact).ln() if operation == "log1p" else exact.exp() - 1
return encode(float(answer), width)
source = ["## Generated by generate_vectors.py from Decimal references; do not edit.",
"import math", "import math32", "",
"func within_ulps(actual: u64, expected: u64) -> bool:",
" let distance = actual - expected if actual >= expected else expected - actual",
" return distance <= 2", "", "pub func check():"]
count = 0
for width in (32, 64):
# Powers of two exercise cancellation; ordinary values exercise each side of
# zero, the logarithm boundary, and a broad range of exponential magnitudes.
values = [sign * 2.0 ** -exponent for exponent in (4, 10, 20, 26, 54, 80, 100)
for sign in (-1, 1)]
values += [-0.999, -0.9, -0.75, -0.5, -0.1, 0.1, 0.5, 1.0, 2.0, 8.0, 20.0]
for operation in ("log1p", "expm1"):
for raw in values:
value = rounded_input(raw, width)
expected = reference(operation, value, width, 160)
assert expected == reference(operation, value, width, 240)
bits = encode(value, width)
module = "math32" if width == 32 else "math"
call = f"{module}.{operation}(f{width}.bits({bits})).bits()"
source.append(f' assert(within_ulps((u64){call}, {expected}), "{module}.{operation} input bits {bits}")')
count += 1
source += [f' print("ok math accuracy: {count} independent vectors")', ""]
(Path(__file__).resolve().parent / "vectors.lucb").write_text("\n".join(source), encoding="utf-8", newline="\n")