iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🗂

Balanced Tridecimal Arithmetic Library

に公開

title: "Balanced Base-13 Calculation Library"
emoji: "🤖"
type: "tech"
topics: ["github", "zenn"]
published: true

No sin, no cos, no differential equations required

Expressing a perfect pentagonal torus using balanced base-13


No sin, no cos, no differential equations required

---"""
B13 Library - Balanced Base-13 Calculation Library

Basic Concepts:

  • B13 = Balanced base-13 {-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6}
  • Achieve all calculations using only addition and subtraction
  • Error control via ±1 rounding
  • Convergence to φ (golden ratio)

Created: 2025-02-15
Author: MORC
License: Public Domain (based on MORC philosophy)
"""

import math

==================== Constants ====================

PHI = (1 + math.sqrt(5)) / 2 # Golden ratio ≈ 1.618
BASE_13 = 13 # Radix for base-13

==================== Fibonacci / Lucas Sequences ====================

def fibonacci(n):
"""
Generate the first n terms of the Fibonacci sequence

F(n) = F(n-1) + F(n-2)
F(0) = 0, F(1) = 1

Returns: [1, 1, 2, 3, 5, 8, 13, 21, ...]
"""
if n <= 0:
    return []
elif n == 1:
    return [1]

fib = [1, 1]
for i in range(2, n):
    fib.append(fib[-1] + fib[-2])
return fib

def lucas(n):
"""
Generate the first n terms of the Lucas sequence

L(n) = L(n-1) + L(n-2)
L(0) = 2, L(1) = 1

Returns: [2, 1, 3, 4, 7, 11, 18, 29, ...]
"""
if n <= 0:
    return []
elif n == 1:
    return [2]

luc = [2, 1]
for i in range(2, n):
    luc.append(luc[-1] + luc[-2])
return luc

def inverse_fibonacci(n):
"""
Inverse Fibonacci sequence (used for error distribution weighting)

Returns: [55, 34, 21, 13, 8, 5, 3, 2, 1, 1]
"""
fib = fibonacci(n)
return fib[::-1]

def magic_number(n):
"""
Calculate magic numbers (2n²)

Related to nuclear/electron shell stability
Returns: 2, 8, 18, 32, 50, 72, 98, ...
"""
return 2 * n * n

==================== B13 Number Class ====================

class B13Number:
"""
Numeric representation in balanced base-13

Each digit coefficient ranges from -6 to +6
"""

def __init__(self, coefficients):
    """
    Args:
        coefficients: List of coefficients [c0, c1, c2, ...]
                     Value = c0 + c1*13 + c2*13² + ...
    """
    self.coeffs = list(coefficients)
    self._normalize()

def _normalize(self):
    """Normalize coefficients to the range of -6 to +6"""
    carry = 0
    for i in range(len(self.coeffs)):
        total = self.coeffs[i] + carry
        
        # Keep within range -6 to +6
        if total > 6:
            self.coeffs[i] = total - BASE_13
            carry = 1
        elif total < -6:
            self.coeffs[i] = total + BASE_13
            carry = -1
        else:
            self.coeffs[i] = total
            carry = 0
    
    # Carry remaining values
    if carry != 0:
        self.coeffs.append(carry)
    
    # Remove trailing zeros
    while len(self.coeffs) > 1 and self.coeffs[-1] == 0:
        self.coeffs.pop()

def to_decimal(self):
    """Convert to decimal"""
    result = 0
    for i, c in enumerate(self.coeffs):
        result += c * (BASE_13 ** i)
    return result

def add(self, other):
    """Addition"""
    max_len = max(len(self.coeffs), len(other.coeffs))
    result = []
    
    for i in range(max_len):
        a = self.coeffs[i] if i < len(self.coeffs) else 0
        b = other.coeffs[i] if i < len(other.coeffs) else 0
        result.append(a + b)
    
    return B13Number(result)

def subtract(self, other):
    """Subtraction"""
    max_len = max(len(self.coeffs), len(other.coeffs))
    result = []
    
    for i in range(max_len):
        a = self.coeffs[i] if i < len(self.coeffs) else 0
        b = other.coeffs[i] if i < len(other.coeffs) else 0
        result.append(a - b)
    
    return B13Number(result)

def __str__(self):
    """String representation"""
    if not self.coeffs:
        return "0"
    
    terms = []
    for i, c in enumerate(self.coeffs):
        if c != 0:
            if i == 0:
                terms.append(f"{c}")
            elif i == 1:
                terms.append(f"{c}*13")
            else:
                terms.append(f"{c}*13^{i}")
    
    return " + ".join(terms) if terms else "0"

def __repr__(self):
    return f"B13({self.coeffs})"

==================== φ (Golden Ratio) Related ====================

def phi_divergence(value, reference=PHI):
"""
Calculate divergence from the golden ratio

Args:
    value: Measured value
    reference: Reference value (default: φ)

Returns:
    Divergence (absolute value)
"""
return abs(value - reference)

def energy_from_phi_divergence(divergence, k=1.0):
"""
Calculate energy from φ divergence

E = k × |value - φ|

Args:
    divergence: Divergence from φ
    k: Proportionality constant

Returns:
    Energy (arbitrary units)
"""
return k * divergence

def is_stable_configuration(ratio, tolerance=0.1):
"""
Determine stability of φ configuration

Args:
    ratio: Measured ratio
    tolerance: Allowable error

Returns:
    True if stable (close to φ)
"""
div = phi_divergence(ratio)
return div < tolerance

==================== Node Processing ====================

def round_to_node(value, node_values=None):
"""
Round to the nearest node value

Args:
    value: Value to round
    node_values: List of nodes (default: B13 nodes)

Returns:
    Nearest node value
"""
if node_values is None:
    node_values = list(range(-6, 7))  # B13 nodes

closest = min(node_values, key=lambda x: abs(x - value))
return closest

def distribute_error_fibonacci(total_error, num_nodes=10):
"""
Distribute error using inverse Fibonacci weights

Args:
    total_error: Total error
    num_nodes: Number of nodes

Returns:
    List of correction values for each node
"""
fib_weights = inverse_fibonacci(num_nodes)
fib_sum = sum(fib_weights)

corrections = []
remaining_error = total_error

for i in range(num_nodes):
    # Sum of remaining weights
    remaining_fib_sum = sum(fib_weights[i:])
    
    # Correction amount at this point
    if remaining_fib_sum > 0:
        correction_target = remaining_error * (fib_weights[i] / remaining_fib_sum)
    else:
        correction_target = 0
    
    # Round to within ±1
    correction = max(-1, min(1, round(correction_target)))
    
    corrections.append(correction)
    remaining_error -= correction

return corrections

==================== Prime Numbers ====================

def is_prime(n):
"""Prime number check"""
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False

for i in range(3, int(math.sqrt(n)) + 1, 2):
    if n % i == 0:
        return False
return True

def prime_pairs_in_range(start, end):
"""
Find prime pairs (twin primes) within a range

Args:
    start: Start value
    end: End value

Returns:
    [(p1, p2), ...] Prime pairs with a difference of 2
"""
primes = [n for n in range(start, end + 1) if is_prime(n)]
pairs = []

for i in range(len(primes) - 1):
    if primes[i + 1] - primes[i] == 2:
        pairs.append((primes[i], primes[i + 1]))

return pairs

def prime_factorization(n):
"""Prime factorization"""
factors = []
d = 2

while d * d <= n:
    while n % d == 0:
        factors.append(d)
        n //= d
    d += 1

if n > 1:
    factors.append(n)

return factors

==================== Utilities ====================

def fibonacci_ratio_convergence(n=20):
"""
Display the convergence of Fibonacci adjacent term ratios to φ

Args:
    n: Number of terms to calculate
"""
fib = fibonacci(n)

print(f"Fibonacci ratio convergence:")
print(f"φ = {PHI:.15f}\n")

for i in range(1, len(fib)):
    ratio = fib[i] / fib[i - 1]
    error = abs(ratio - PHI)
    print(f"F({i+1})/F({i}) = {fib[i]}/{fib[i-1]} = {ratio:.15f}, Error: {error:.2e}")

def lucas_ratio_convergence(n=20):
"""
Display the convergence of Lucas adjacent term ratios to φ
"""
luc = lucas(n)

print(f"Lucas ratio convergence:")
print(f"φ = {PHI:.15f}\n")

for i in range(1, len(luc)):
    ratio = luc[i] / luc[i - 1]
    error = abs(ratio - PHI)
    print(f"L({i+1})/L({i}) = {luc[i]}/{luc[i-1]} = {ratio:.15f}, Error: {error:.2e}")

def compare_fibonacci_lucas_magic(n=10):
"""
Compare Fibonacci, Lucas, and Magic numbers
"""
fib = fibonacci(n)
luc = lucas(n)
magic = [magic_number(i) for i in range(1, n + 1)]

print("n\tFib\tLucas\tMagic\tFib+Luc")
print("-" * 50)
for i in range(n):
    f = fib[i] if i < len(fib) else 0
    l = luc[i] if i < len(luc) else 0
    m = magic[i]
    print(f"{i+1}\t{f}\t{l}\t{m}\t{f+l}")

==================== Tests / Demos ====================

def demo_b13_arithmetic():
"""B13 arithmetic demo"""
print("=" * 60)
print("B13 Arithmetic Demo")
print("=" * 60)
print()

# Create numbers
num1 = B13Number([3, -2, 1])
num2 = B13Number([5, 1, -1])

print(f"num1 = {num1}")
print(f"num1 (decimal) = {num1.to_decimal()}")
print()

print(f"num2 = {num2}")
print(f"num2 (decimal) = {num2.to_decimal()}")
print()

# Addition
result_add = num1.add(num2)
print(f"num1 + num2 = {result_add}")
print(f"Result (decimal) = {result_add.to_decimal()}")
print(f"Verification: {num1.to_decimal()} + {num2.to_decimal()} = {num1.to_decimal() + num2.to_decimal()}")
print()

# Subtraction
result_sub = num1.subtract(num2)
print(f"num1 - num2 = {result_sub}")
print(f"Result (decimal) = {result_sub.to_decimal()}")
print(f"Verification: {num1.to_decimal()} - {num2.to_decimal()} = {num1.to_decimal() - num2.to_decimal()}")

def demo_phi_divergence():
"""φ divergence demo"""
print("\n" + "=" * 60)
print("φ Divergence and Energy")
print("=" * 60)
print()

print(f"Golden ratio φ = {PHI:.15f}")
print()

test_values = [1.0, 1.5, 1.6, 1.618, 1.7, 2.0]

print("Value\tDivergence\tEnergy\tStability")
print("-" * 60)
for val in test_values:
    div = phi_divergence(val)
    energy = energy_from_phi_divergence(div)
    stable = "Stable" if is_stable_configuration(val) else "Unstable"
    print(f"{val:.3f}\t{div:.6f}\t{energy:.6f}\t{stable}")

def demo_error_distribution():
"""Error distribution demo"""
print("\n" + "=" * 60)
print("Error Distribution via Inverse Fibonacci")
print("=" * 60)
print()

total_error = 10.0
num_nodes = 10

corrections = distribute_error_fibonacci(total_error, num_nodes)

print(f"Total Error: {total_error}")
print(f"Number of nodes: {num_nodes}")
print()

print("Node\tCorrection")
print("-" * 30)
for i, corr in enumerate(corrections):
    print(f"{i}\t{corr}")

print()
print(f"Correction Sum: {sum(corrections)}")
print(f"Residual Error: {total_error - sum(corrections)}")

def demo_prime_magic():
"""Prime and Magic number demo"""
print("\n" + "=" * 60)
print("Primes and Magic Numbers")
print("=" * 60)
print()

print("Magic numbers (2n²):")
for n in range(1, 11):
    m = magic_number(n)
    factors = prime_factorization(m)
    print(f"n={n}: 2×{n}² = {m} = {' × '.join(map(str, factors))}")

print()
print("Critical range 48-52:")
for n in range(48, 53):
    factors = prime_factorization(n)
    prime_status = "Prime" if is_prime(n) else "Composite"
    print(f"{n}: {prime_status}, Prime factorization = {' × '.join(map(str, factors))}")

==================== Main Execution ====================

if name == "main":
"""
Run library demo

Executing this file directly will display demos for each function
"""

print("B13 Library - MORC Project")
print("=" * 60)
print()

# Run each demo
demo_b13_arithmetic()
demo_phi_divergence()
demo_error_distribution()
demo_prime_magic()

print("\n" + "=" * 60)
print("All demos complete")
print("=" * 60)
print()
print("This library can be imported and used as follows:")
print()
print("    from b13_library import *")
print()
print("    # Fibonacci sequence")
print("    fib = fibonacci(10)")
print()
print("    # B13 arithmetic")
print("    num = B13Number([1, 2, -3])")
print("    result = num.add(B13Number([3, -1, 1]))")
print()
print("    # φ divergence")
print("    div = phi_divergence(1.6)")
print("    energy = energy_from_phi_divergence(div)")
print()", "completed": true}

Discussion