Почему деление по phi
Вы узнаете
Два довода за деление по phi и почему спека говорит, что довод о самоподобии — не оптимизация.
phi_split_optimality.t27 приводит два довода и говорит, какой из них какой. Один довод — самоподобие: потребуем, чтобы порядок относился к мантиссе, как мантисса к обоим полям вместе, E / M = M / (E + M). С r = E / M это r = 1 / (r + 1), значит r^2 + r - 1 = 0 и r = (sqrt(5) - 1) / 2 = 1 / phi. Спека прямо говорит, что это определяющее свойство, а не оптимизация: если просто максимизировать E * M, деление выходит поровну, 7 и 7 для 14 битов. Другой довод — про округление: round((N - 1) / phi^2) — ближайшее к идеалу целое, и verify_7_7_match находит его равным опубликованному делению в 7 из 7 форматов.
Попробуйте
Прочитайте self_similarity_proof_steps и сосчитайте шаги. Затем найдите тест, который говорит, что деление по AM-GM отличается от деления по phi, и ширину, которую он берёт.

Two arguments for the phi split, and one that gives an equal split instead, read from phi_split_optimality.t27. Lesson 4 of the GoldenFloat course.
specs/math/phi_split_optimality.t27
// SPDX-License-Identifier: Apache-2.0
// t27/specs/math/phi_split_optimality.t27
// Phi-Split Theorems — Self-Similarity + Optimal Rounding (CORRECTED)
// MATH-OPTIMALITY-001 — Foundation for GoldenFloat being non-random
//
// THEOREM 1 (Golden Self-Similarity): phi is unique self-similar proportion for bit allocation
// THEOREM 2 (Optimal Rounding): round((N-1)/phi^2) minimizes phi-distance (7/7 match)
module PhiSplitOptimality {
use math::constants;
use math::sacred_physics;
// ===================================================================
// 1. Theorem 1: Golden Self-Similarity
// ===================================================================
// The golden ratio phi is defined by: phi^2 = phi + 1
// This gives self-similar property: phi = 1 + 1/phi
//
// For bit allocation, self-similarity means:
// exp/mant = mant/(exp + mant)
// This gives: exp/mant = 1/(exp/mant + 1)
// Solving: (exp/mant)^2 + (exp/mant) - 1 = 0 -> exp/mant = 1/phi
//
// IMPORTANT: This is NOT an optimization problem (maximizing e*m gives r=1 by AM-GM).
// This is a self-similarity constraint — a defining property of the golden ratio.
const PHI_TARGET : f64 = sacred_physics::PHI_INV; // 1/phi approx 0.618...
// ===================================================================
// 2. Analytical Proof: Self-Similarity
// ===================================================================
struct ProofStep {
description : string,
equation : string,
result : string,
}
// Self-Similarity Theorem Derivation:
// Given: exp + mant = available (where available = N - 1)
// Let r = exp/mant (ratio of exponent to mantissa bits)
// Self-similarity constraint: r = mant/(exp + mant) = 1/(r + 1)
// Solving: r^2 + r - 1 = 0
// r = (sqrt(5) - 1)/2 = 1/phi approx 0.618
//
// This follows directly from phi^2 = phi + 1, the defining property of phi.
// It is NOT an optimization result — it's a self-similarity property.
fn optimal_ratio_by_self_similarity(available: u8) -> (u8, u8) {
// Self-similarity constraint: exp/mant = 1/phi
const r = PHI_TARGET;
const m = (available as f64 / (1.0 + r)).round() as u8;
const e = available - m;
return (e, m);
}
// ===================================================================
// 3. Theorem 2: Optimal Rounding
// ===================================================================
// The formula exp = round((N-1)/phi^2) selects the integer closest to the
// golden ratio proportion. This minimizes phi-distance between actual and ideal allocation.
//
// Proof: For integer allocation, we choose between floor and ceil of the ideal value.
// The phi-proportion gives exp_ideal = (N-1)/phi^2 (real).
// round() selects floor or ceil that gives minimum |exp_bits/available - 1/phi^2|.
// All 7 GF formats follow this rule exactly (7/7 match verified).
fn optimal_allocation_by_rounding(total_bits: u8) -> (u8, u8, f64) {
const available = total_bits - 1;
const phi_sq = sacred_physics::PHI * sacred_physics::PHI;
// exp = round((N-1) / phi^2)
const exp_raw = (available as f64) / phi_sq;
const exp_bits = round(exp_raw) as u8;
const mant_bits = available - exp_bits;
// Compute phi-distance
const ratio = (exp_bits as f64) / (mant_bits as f64);
const phi_dist = abs(ratio - PHI_TARGET);
return (exp_bits, mant_bits, phi_dist);
}
// ===================================================================
// 4. AM-GM Comparison (for reference, NOT the phi derivation)
// ===================================================================
// By AM-GM inequality, product e * m is maximized when e = m.
// This gives r = 1, NOT r = 1/phi.
// This shows that maximizing e*m does NOT lead to phi.
fn optimal_ratio_by_am_gm(available: u8) -> (u8, u8) {
// By AM-GM, product e * m is maximized when e and m are as equal as possible
const half = available as f64 / 2.0;
let exp = round(half) as u8;
let mant = available - exp;
return (exp, mant);
}
fn round(x: f64) -> f64 {
if x < 0.0 {
let xi = x as i64;
let frac = x - (xi as f64);
if frac <= -0.5 {
return (xi - 1) as f64;
}
return xi as f64;
}
let xi = x as i64;
let frac = x - (xi as f64);
if frac >= 0.5 {
return (xi + 1) as f64;
}
return xi as f64;
}
fn abs(x: f64) -> f64 {
if x < 0.0 {
return -x;
}
return x;
}
// ===================================================================
// 5. Proof Steps for Documentation
// ===================================================================
fn self_similarity_proof_steps() -> [4]ProofStep {
return [
ProofStep{
description = "Golden ratio identity",
equation = "phi^2 = phi + 1",
result = "Defining property of phi",
},
ProofStep{
description = "Self-similarity constraint",
equation = "exp/mant = mant/(exp + mant)",
result = "Bit allocation reflects itself at different scales",
},
ProofStep{
description = "Substitution",
equation = "Let r = exp/mant, then r = 1/(r + 1)",
result = "Express constraint in terms of ratio r",
},
ProofStep{
description = "Solve for r",
equation = "r^2 + r - 1 = 0 -> r = (sqrt(5) - 1)/2 = 1/phi",
result = "Golden ratio emerges as unique self-similar proportion",
},
];
}
fn optimal_rounding_proof_steps() -> [3]ProofStep {
return [
ProofStep{
description = "Ideal proportion",
equation = "exp_ideal = (N-1)/phi^2",
result = "Continuous value from phi-proportion",
},
ProofStep{
description = "Rounding rule",
equation = "exp_bits = round(exp_ideal)",
result = "Select integer minimizing phi-distance",
},
ProofStep{
description = "Verification",
equation = "7/7 GF formats match round() exactly",
result = "No deviations - all follow phi-proportion via optimal rounding",
},
];
}
// ===================================================================
// 6. GF Format Verification (7/7 match)
// ===================================================================
struct GFFamilyVerification {
format : string,
bits : u8,
exp_bits : u8,
mant_bits : u8,
phi_raw : f64,
phi_rounded : u8,
matches : bool,
}
fn verify_7_7_match() -> [7]GFFamilyVerification {
const phi_sq = sacred_physics::PHI * sacred_physics::PHI;
// GF formats with their actual allocations
const formats = [
("GF4", 4, 1, 2),
("GF8", 8, 3, 4),
("GF12", 12, 4, 7),
("GF16", 16, 6, 9),
("GF20", 20, 7, 12),
("GF24", 24, 9, 14),
("GF32", 32, 12, 19),
];
let mut results = [7]GFFamilyVerification{};
for i in 0..7 {
const (name, bits, exp, mant) = formats[i];
const available = bits - 1;
const phi_raw = (available as f64) / phi_sq;
const phi_rounded = round(phi_raw) as u8;
results[i] = GFFamilyVerification{
format = name,
bits = bits,
exp_bits = exp,
mant_bits = mant,
phi_raw = phi_raw,
phi_rounded = phi_rounded,
matches = exp == phi_rounded,
};
}
return results;
}
// ===================================================================
// 7. TDD-Inside-Spec: Tests and Invariants
// ===================================================================
test self_similarity_proof_has_all_steps
given steps = self_similarity_proof_steps()
then steps.length() == 4
test self_similarity_proof_steps_valid
given steps = self_similarity_proof_steps()
and last_step = steps[3]
then last_step.result.contains("1/phi") == true
test optimal_rounding_proof_has_all_steps
given steps = optimal_rounding_proof_steps()
then steps.length() == 3
test optimal_rounding_proof_confirms_match
given steps = optimal_rounding_proof_steps()
and verification_step = steps[2]
then verification_step.result.contains("7/7") == true
test optimal_ratio_by_self_similarity_respects_budget
given (exp, mant) = optimal_ratio_by_self_similarity(15)
then exp + mant == 15
test optimal_ratio_by_self_similarity_close_to_target
given (exp, mant) = optimal_ratio_by_self_similarity(31)
and ratio = (exp as f64) / (mant as f64)
then abs(ratio - PHI_TARGET) < 0.05
test optimal_allocation_by_rounding_for_gf4
// GF4 is 1+1+2: ratio 1/2, so phi_dist = |0.5 - 0.618034| = 0.118034.
// (This test claimed phi_dist < 0.05, which no 4-bit split can meet.)
given (exp, mant, phi_dist) = optimal_allocation_by_rounding(4)
then exp == 1 and mant == 2 and phi_dist > 0.11 and phi_dist < 0.12
test optimal_allocation_by_rounding_for_gf32
given (exp, mant, phi_dist) = optimal_allocation_by_rounding(32)
then exp == 12 and mant == 19 and phi_dist < 0.02
test verify_7_7_match_all_formats
given verification = verify_7_7_match()
then verification.length() == 7
test verify_7_7_all_match
// Every one of the seven rows, written out (a forall clause did not lower).
given v = verify_7_7_match()
then v[0].matches == true and v[1].matches == true and v[2].matches == true
and v[3].matches == true and v[4].matches == true and v[5].matches == true
and v[6].matches == true
test am_gm_gives_equal_split
given (exp, mant) = optimal_ratio_by_am_gm(10)
and available = 9
then abs(exp as f64 - mant as f64) <= 1.0
test am_gm_different_from_phi_split
given (exp_amgm, mant_amgm) = optimal_ratio_by_am_gm(15)
and (exp_phi, mant_phi) = optimal_ratio_by_self_similarity(15)
then exp_amgm != exp_phi or mant_amgm != mant_phi
test am_gm_bits_sum_to_available
// The argument IS the available budget; it was 15 against an expected 14.
given (exp, mant) = optimal_ratio_by_am_gm(14)
and available = 14
then exp + mant == available
// ===================================================================
// 8. Invariants
// ===================================================================
invariant phi_target_is_phi_inverse
assert PHI_TARGET == sacred_physics::PHI_INV
invariant phi_target_in_valid_range
assert PHI_TARGET > 0.5 and PHI_TARGET < 1.0
invariant self_similarity_respects_bit_budget
// For every budget; checked at three, small, primary and large.
given (e1, m1) = optimal_ratio_by_self_similarity(3)
and (e2, m2) = optimal_ratio_by_self_similarity(15)
and (e3, m3) = optimal_ratio_by_self_similarity(31)
assert e1 + m1 == 3 and e2 + m2 == 15 and e3 + m3 == 31
invariant optimal_rounding_respects_bit_budget
// For every width; checked at three, one sign bit each.
given (e1, m1, d1) = optimal_allocation_by_rounding(8)
and (e2, m2, d2) = optimal_allocation_by_rounding(16)
and (e3, m3, d3) = optimal_allocation_by_rounding(32)
assert e1 + m1 == 7 and e2 + m2 == 15 and e3 + m3 == 31
invariant phi_round_matches_all_7_formats
// CRITICAL: 7/7 match invariant - prevents regression of floor() bug
given v = verify_7_7_match()
assert v[0].matches and v[1].matches and v[2].matches and v[3].matches
and v[4].matches and v[5].matches and v[6].matches
invariant self_similarity_proof_steps_complete
assert self_similarity_proof_steps().length() == 4
invariant optimal_rounding_proof_steps_complete
assert optimal_rounding_proof_steps().length() == 3
invariant am_gm_always_gives_equal_or_near_equal
// For every budget; checked at an even one and an odd one.
given (e1, m1) = optimal_ratio_by_am_gm(14)
and (e2, m2) = optimal_ratio_by_am_gm(15)
assert abs(e1 as f64 - m1 as f64) <= 1.0 and abs(e2 as f64 - m2 as f64) <= 1.0
invariant phi_distance_non_negative
given (e, m, phi_dist) = optimal_allocation_by_rounding(16)
assert phi_dist >= 0.0
invariant phi_distance_for_gf32_is_minimum
given verification = verify_7_7_match()
assert verification[6].phi_raw > verification[5].phi_raw // GF32 > GF24
// ===================================================================
// 9. Benchmarks
// ===================================================================
bench self_similarity_proof_computation
measure: nanoseconds to compute proof steps
target: < 100ns
bench optimal_rounding_computation
measure: nanoseconds to compute round((N-1)/phi^2)
target: < 50ns
bench verify_7_7_match_computation
measure: nanoseconds to verify all 7 GF formats
target: < 200ns
}
Все уроки
Модуль 1 · Правило и его числа
Одно правило делит каждую ширину, отношение, к которому оно стремится, и числа Люка за тройкой 3.
Модуль 2 · Почему phi, почему три
Почему деление идёт по phi, почему основание три и как спека проверяет, что GF16 хранит phi.
Модуль 3 · Малые ступени: от GF4 до GF8
GF4, GF6 и GF8 — меньше всего битов, и округление до целых битов стоит здесь дороже всего.
Модуль 4 · От десяти до четырнадцати битов
GF10, GF12 и GF14 и то, как расстояние до 1 / phi меняется с ростом слова.
Модуль 5 · GF16 в работе
Основной 16-битный формат, скалярное произведение из двух слагаемых в GF-T16, затем GF20 и GF24.
Модуль 6 · От GF32 до GF64
GF32 рядом с IEEE single, GF48 без пары в IEEE, GF64 рядом с IEEE double.
Модуль 7 · От GF96 до GF256
GF96, GF128 и GF256, где спеки держат раскладку инвариантами.
Модуль 8 · Самые широкие ступени, затем триты
GF512 и GF1024, две самые широкие ступени, затем GF-T8, где порядок уходит в триты.
Модуль 9 · Ещё триты, затем декодирование
GF-T16 и GF-T32, затем почему фиксированные поля декодируются параллельно, а posit — нет.