Repository navigation
Expand file tree
/
Copy pathgen_compute_table.py
More file actions
executable file
·85 lines (69 loc) · 2.59 KB
/
Copy pathgen_compute_table.py
File metadata and controls
executable file
·85 lines (69 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
"""Generate the FACTOR ASERT log2(compute) lookup table.
Formula: log2_compute(n) = 0.0301 * log2(R) * n + 2 * log2(n)
where R = 3.8 and n is an even integer in [2, 1022].
Output: C++ header with 511-entry Q32.32 fixed-point int64_t array.
Usage: python3 scripts/gen_compute_table.py > src/asert_table.h
"""
import decimal
import hashlib
import sys
# Parameters
R = decimal.Decimal("3.8")
COEFF = decimal.Decimal("0.0301")
NBITS_MIN = 2
NBITS_MAX = 1022
Q32 = 2**32
def log2_decimal(x: decimal.Decimal) -> decimal.Decimal:
"""Compute log2(x) in high-precision Decimal arithmetic."""
return x.ln() / decimal.Decimal(2).ln()
def main():
decimal.getcontext().prec = 60
log2_R = log2_decimal(R)
entries: list[tuple[int, int]] = []
prev = None
for i in range(511):
n = 2 * (i + 1) # even integers 2, 4, 6, ..., 1022
log2_n = log2_decimal(decimal.Decimal(n))
value = COEFF * log2_R * n + 2 * log2_n
q32_value = int(
(value * Q32).to_integral_value(rounding=decimal.ROUND_HALF_EVEN)
)
if prev is not None:
assert q32_value > prev, (
f"Table not monotonically increasing at nBits={n}: "
f"{q32_value} <= {prev}"
)
prev = q32_value
entries.append((n, q32_value))
lines: list[str] = []
lines.append("// Copyright (c) 2026 The FACTOR developers")
lines.append("// Distributed under the MIT software license, see the accompanying")
lines.append(
"// file COPYING or http://www.opensource.org/licenses/mit-license.php."
)
lines.append("")
lines.append("#ifndef BITCOIN_ASERT_TABLE_H")
lines.append("#define BITCOIN_ASERT_TABLE_H")
lines.append("")
lines.append("#include <cstdint>")
lines.append("")
lines.append(
"// log2(compute(nBits)) in Q32.32 fixed-point for every valid even nBits."
)
lines.append("// Index i corresponds to nBits = 2*(i+1).")
lines.append("// Formula: log2_compute(n) = 0.0301 * log2(3.8) * n + 2 * log2(n)")
lines.append("// Generated by scripts/gen_compute_table.py")
lines.append("inline constexpr int64_t LOG2_COMPUTE_TABLE[511] = {")
for n, val in entries:
lines.append(f" {val:>20}LL, /* nBits={n:4d} */")
lines.append("};")
lines.append("")
lines.append("#endif // BITCOIN_ASERT_TABLE_H")
lines.append("")
output = "\n".join(lines)
_ = sys.stdout.write(output)
sha = hashlib.sha256(output.encode("utf-8")).hexdigest()
print(f"SHA-256: {sha}", file=sys.stderr)
if __name__ == "__main__":
main()