Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1import bisect3INPUT_BITS = 324TABLE_BITS = 55INT_BITS = 646EXACT_FPBITS = 2568F = RealField(100) # overkill10def BestOverApproxInvLog2(mulof, maxd):11"""12Compute denominator of an approximation of 1/log(2).14Specifically, find the value of d (<= maxd, and a multiple of mulof)15such that ceil(d/log(2))/d is the best approximation of 1/log(2).16"""17dist=118best=019# Precomputed denominators that lead to good approximations of 1/log(2)20for d in [1, 2, 9, 70, 131, 192, 445, 1588, 4319, 11369, 18419, 25469, 287209, 836158, 3057423, 8336111, 21950910, 35565709, 49180508, 161156323, 273132138, 385107953, 882191721]:21kd = lcm(mulof, d)22if kd <= maxd:23n = ceil(kd / log(2))24dis = F((n / kd) - 1 / log(2))25if dis < dist:26dist = dis27best = kd28return best31LOG2_TABLE = []32A = 033B = 034C = 035D = 036K = 038def Setup(k):39global LOG2_TABLE, A, B, C, D, K40K = k41LOG2_TABLE = []42for i in range(2 ** TABLE_BITS):43LOG2_TABLE.append(int(floor(F(K * log(1 + i / 2**TABLE_BITS, 2)))))45# Maximum for (2*x+1)*LogK2(x)46max_T = (2^(INPUT_BITS + 1) - 1) * (INPUT_BITS*K - 1)47# Maximum for A48max_A = (2^INT_BITS - 1) // max_T49D = BestOverApproxInvLog2(2 * K, max_A * 2 * K)50A = D // (2 * K)51B = int(ceil(F(D/log(2))))52C = int(floor(F(D*log(2*pi,2)/2)))54def LogK2(n):55assert(n >= 1 and n < (1 << INPUT_BITS))56bits = Integer(n).nbits()57return K * (bits - 1) + LOG2_TABLE[((n << (INPUT_BITS - bits)) >> (INPUT_BITS - TABLE_BITS - 1)) - 2**TABLE_BITS]59def Log2Fact(n):60# Use formula (A*(2*x+1)*LogK2(x) - B*x + C) / D61return (A*(2*n+1)*LogK2(n) - B*n + C) // D + (n < 3)63RES = [int(F(log(factorial(i),2))) for i in range(EXACT_FPBITS * 10)]65best_worst_ratio = 067for K in range(1, 10000):68Setup(K)69assert(LogK2(1) == 0)70assert(LogK2(2) == K)71assert(LogK2(4) == 2 * K)72good = True73worst_ratio = 174for i in range(1, EXACT_FPBITS * 10):75exact = RES[i]76approx = Log2Fact(i)77if not (approx <= exact and ((approx == exact) or (approx >= EXACT_FPBITS and exact >= EXACT_FPBITS))):78good = False79break80if worst_ratio * exact > approx:81worst_ratio = approx / exact82if good and worst_ratio > best_worst_ratio:83best_worst_ratio = worst_ratio84print("Formula: (%i*(2*x+1)*floor(%i*log2(x)) - %i*x + %i) / %i; log(max_ratio)=%f" % (A, K, B, C, D, RR(-log(worst_ratio))))85print("LOG2K_TABLE: %r" % LOG2_TABLE)
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.