Skip to main content

tritlib — v2.0

A pure Python library for balanced ternary arithmetic, multi-valued logic, and floating-point representation.

Overview

Balanced ternary is a base-3 numeral system using digits from {−1, 0, +1}. It represents signed integers without a dedicated sign bit, supports trivial negation by inverting every trit, and simplifies carry propagation in addition. tritlib provides a complete, immutable, type-hinted implementation of balanced ternary arithmetic, five ternary logic systems, and the Tekum tapered precision floating-point format.

Features

Core types

  • Trit — Immutable single trit. Arithmetic (negation, multiplication, half/full addition with ternary carry), Kleene K3 logic (&, |, ~), consensus and anti-consensus operators. Hashable and comparable.
  • Trits — Arbitrary-precision balanced ternary integer. Full arithmetic: addition, subtraction, multiplication, floor division and modulo via the double trial quotient method. Constructed from int or balanced ternary string ("+-0+").
  • TritArray — Fixed-width ternary word at arbitrary width, analogous to a hardware register. Three addition modes: truncating (wrap around), with carry, and saturating. Shifts, rotations, trit-level access and modification, sign extraction, absolute value, consensus/anti-consensus. Resizable across widths via to_width.
  • Trybble / Tryte / Word — Width-locked subclasses of TritArray matching the Setnex ISA unit hierarchy: 3 trits (T3, register address / sub-opcode), 9 trits (T9, byte-analogue), and 27 trits (T27, memory and register word). All inherit TritArray's arithmetic and preserve their concrete type through operations.
  • TFloat — Balanced ternary floating-point number using the Tekum tapered precision format (Hunhold, arXiv:2512.10964). No sign trit, truncation equals rounding, three special values (zero, infinity, NaR). Configurable width (even, ≥ 8). Addition, multiplication and division all use native trit-level arithmetic with wheel-algebra semantics for the special values.

Multi-valued logic

Five ternary logic systems, selectable at runtime via a common abstract interface:

System Third value semantics Key difference
Kleene (K3) Unknown (epistemic) Default. AND = min, OR = max
Łukasiewicz (L3) Indeterminate (ontological) Z → Z yields P (tautological self-implication)
Heyting (HT) Non-proved (constructivist) ~Z = N (unproved is false)
B3 (Bochvar) Meaningless (infectious) Z is absorbing: Z ∧ Z = Z ∨ Z = Z → Z = Z
RM3 (R-mingle) Relevant entailment Restricted implication

Each system implements NOT, AND, OR, IMPLY, XOR, and EQUIV. Custom systems can be added by subclassing TernaryLogic. The logic_mode context manager switches the active logic system for operators on Trit. The pluralize function evaluates an expression across all five systems and reports convergence or divergence.

Designed for simulation

tritlib provides the building blocks for balanced ternary processor simulation:

  • Ternary carry (N/Z/P) richer than binary carry (0/1)
  • add_with_carry / add_saturating / sub_saturating for ALU mode selection
  • Shift and rotate operations
  • Per-trit access (__getitem__) and immutable modification (set)
  • Sign extraction and absolute value
  • Consensus / anti-consensus (trit-level agreement detection)
  • Logic system dispatch independent of data types (LMODE selection)
  • Tekum floating-point decode/encode for FPU simulation

Installation

pip install tritlib

Requires Python ≥ 3.11. No external dependencies.

Usage

Trit arithmetic

from tritlib import Trit, P, Z, N

t = Trit(1)
print(t)          # "+"
print(-t)         # "-"

# Half-adder: returns (sum, carry)
s, c = P.half_add(P)    # s = N, c = P  (1+1 = 3−1)

# Kleene logic
assert (P & Z) == Z     # true AND unknown = unknown
assert (N | P) == P     # false OR true = true

Arbitrary-precision integers

from tritlib import Trits

a = Trits(42)
b = Trits("+-0+")       # 19 in balanced ternary
print(a + b)             # Trits("+-+-+") == Trits(61)
print(int(a * b))        # 798

q, r = divmod(Trits(13), Trits(4))
assert int(q) * 4 + int(r) == 13

# The remainder is balanced: |r| <= |divisor| / 2, so it takes
# whichever sign minimises its magnitude — not the dividend's.
q, r = divmod(Trits(40), Trits(6))
assert int(q) * 6 + int(r) == 40
print(int(q))  # 7
print(int(r))  # -2

Fixed-width words

from tritlib import TritArray, Trybble, Tryte, Word

# ISA-aligned width-locked types
print(len(Trybble(1)))        # 3
print(len(Tryte(42)))         # 9
print(len(Word(0)))           # 27

# Arbitrary width via TritArray
w = TritArray(42, width=6)
print(len(w))                 # 6
print(w[0])                   # least significant trit

# Saturating addition (any TritArray subclass)
result = TritArray(300, 6).add_saturating(TritArray(300, 6))
print(int(result))            # 364 (clamped to max)

# Carry detection
result, carry = TritArray(300, 6).add_with_carry(TritArray(65, 6))
print(carry)                  # P (positive overflow)

Floating-point (Tekum format)

from tritlib import TFloat, TritArray

# Encode from Python float
tf = TFloat(3.14, width=20)
print(float(tf))              # ≈ 3.14

# Decode from a register word (even width ≥ 8)
register = TritArray(1640, 8)
tf = TFloat(register)
print(float(tf))              # 1.0

# Arithmetic
a = TFloat(2.5, width=20)
b = TFloat(1.3, width=20)
print(float(a + b))           # ≈ 3.8
print(float(a * b))           # ≈ 3.25
print(float(a / b))           # ≈ 1.923

# Special values
print(TFloat(0.0, width=8))             # 0
print(TFloat(float('inf'), width=8))    # ∞
print(TFloat(float('nan'), width=8))    # NaR

Logic systems

from tritlib import P, Z, N
from tritlib.logic import Kleene, Lukasiewicz, HT, Bochvar, RM3

k = Kleene()
l = Lukasiewicz()

# The single point of divergence:
assert k.imply_op(Z, Z) == Z    # unknown → unknown = unknown
assert l.imply_op(Z, Z) == P    # indeterminate → indeterminate = true

# Context manager
from tritlib import logic_mode

assert Z & N == N
with logic_mode(Bochvar()):
    assert N & Z == Z

assert Z.imply(Z) == Z
with logic_mode(Lukasiewicz()):
    assert Z.imply(Z) == P

assert ~Z == Z
with logic_mode(HT()):
    assert ~Z == N

Logical pluralism

from tritlib import P, Z, N
from tritlib.logic.plural import pluralize

# Evaluate Z → Z across all five logic systems
result = pluralize(lambda a, b: a.imply(b), Z, Z)
print(result.divergent)   # True — logics disagree
print(result.groups)      # {Trit(0): ['BI3', 'K3', 'RM3'], Trit(1): ['HT', 'L3']}
print(result.consensus)   # None — no unanimous agreement

Project structure

src/tritlib/
├── __init__.py
├── trit.py            # Trit type
├── trits.py           # Trits arbitrary-precision type
├── tritarray.py       # TritArray generic fixed-width type
├── trybble.py         # Trybble (T3, 3-trit subclass)
├── tryte.py           # Tryte (T9, 9-trit subclass)
├── word.py            # Word (T27, 27-trit subclass)
├── tfloat.py          # TFloat Tekum floating-point type
├── context.py         # Logic mode context manager
└── logic/
    ├── __init__.py
    ├── base.py        # TernaryLogic abstract base class
    ├── plural.py      # Logical pluralism (pluralize)
    ├── bochvar.py     # Bochvar
    ├── heyting.py     # Heyting HT
    ├── kleene.py      # Kleene K3
    ├── lukasiewicz.py # Łukasiewicz L3
    └── rm3.py         # R-mingle RM3

Development

git clone https://codeberg.org/setnex-org/tritlib.git
cd tritlib
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
python -m pytest

Roadmap

  • Trit type with immutability, arithmetic, hashing, consensus
  • Kleene K3 logic on Trit (&, |, ~)
  • Trits arbitrary-precision integers with full arithmetic
  • Tryte fixed-width words with shifts, rotations, saturation
  • Five logic systems (K3, L3, HT, BI3, RM3) with common interface
  • Logic context manager (with logic_mode(L3()): result = a & b)
  • Logical pluralism: evaluate across all systems, report convergence/divergence
  • Tekum balanced ternary floating-point (encode, decode, arithmetic via float)
  • Native trit-level __add__, __mul__ and __truediv__ (Tekum truncation = rounding)
  • Educational step-by-step computation output (carry propagation, partial products)

License

MIT — see LICENSE file for details.

Metadata

Release files for tritlib 2.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tritlib 2.1.1
File Size Uploaded Provenance
tritlib-2.1.1.tar.gz 45.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for tritlib 2.1.1
File Interpreter ABI Platform
tritlib-2.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 77.5 kB

Release files / tritlib-2.1.1.tar.gz

Download URL tritlib-2.1.1.tar.gz
Size 45.5 kB
Tags Source
SHA-256 checksum
How to use checksums
fc91c1cb983e3621e0490d9da8362cdcc8ac1118b97bfa9e07a8513fdccc8266
BLAKE2b-256 checksum
How to use checksums
76462040a89e43afc24a240610d31711395470b06ca8cd095f2b1099d0adf0fd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.6

Release files / tritlib-2.1.1-py3-none-any.whl

Download URL tritlib-2.1.1-py3-none-any.whl
Size 32.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f0a328eac2fa4ca4ca29f13b5a42f2da488b55b4cdb0d7bd0d036de8a2c4b200
BLAKE2b-256 checksum
How to use checksums
404d8589e686a1d37a5f595592ed6ec6141f243eaef5340b4b6e5d904b915f46
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.6

Security for tritlib 2.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page