Skip to main content

Balanced ternary arithmetic and multi-valued logic library

Project description

tritlib

A pure Python library for balanced ternary arithmetic and multi-valued logic.

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 and five ternary logic systems.

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+").
  • Tryte — Fixed-width ternary word, 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.

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)
BI3 Both true and false (paraconsistent) Z ∧ Z = N (contradiction resolves downward)
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.

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)

Installation

pip install tritlib

Requires Python ≥ 3.10. 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

# Division can have nevative remainder
q, r = divmod(Trits(20), Trits(6))
assert int(q) * 6 + int(r) == 20
print(int(q)) # 4
print(int(r)) # -4 

Fixed-width words

from tritlib import Tryte

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

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

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

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 Z, N, P, logic_mode, Lukasiewicz, Bochvar, RM3, HT

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.imply(N) == Z
assert P.imply(Z) == Z
with logic_mode(RM3()):
    assert Z.imply(N) == N
    assert Z.imply(Z) == Z
    assert P.imply(Z) == N


assert Z|P == P
with logic_mode(Bochvar()):
    assert Z|P == Z

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

Project structure

src/tritlib/
├── __init__.py
├── trit.py            # Trit type
├── trits.py           # Trits arbitrary-precision type
├── tryte.py           # Tryte fixed-width type
└── logic/
    ├── __init__.py
    ├── base.py        # TernaryLogic abstract base class
    ├── 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/newick_2/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 tritlib.logic_mode(L3): result = a & b)
  • Logical pluralism: evaluate an expression across all logic systems and report convergence/divergence
  • Balanced ternary floating-point representation
  • Educational step-by-step computation output (carry propagation, partial products)

License

MIT — see LICENSE file for details.

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tritlib-0.6.0.tar.gz (14.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tritlib-0.6.0-py3-none-any.whl (17.6 kB view details)

Uploaded Python 3

File details

Details for the file tritlib-0.6.0.tar.gz.

File metadata

  • Download URL: tritlib-0.6.0.tar.gz
  • Upload date:
  • Size: 14.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for tritlib-0.6.0.tar.gz
Algorithm Hash digest
SHA256 ede99f3ef1cca717d643340ed7751d0308aaeb470b5ca1ab9bc8c123d9bf7da2
MD5 5c0e5e51755011f2cc0569f658422aa2
BLAKE2b-256 7044b38ce4099a2a84783b1eb45176b649cdc5bf9a259cced038faaa368d5b21

See more details on using hashes here.

File details

Details for the file tritlib-0.6.0-py3-none-any.whl.

File metadata

  • Download URL: tritlib-0.6.0-py3-none-any.whl
  • Upload date:
  • Size: 17.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for tritlib-0.6.0-py3-none-any.whl
Algorithm Hash digest
SHA256 30113f30026360ccc71e8d6a0b86a2613df71672ef494deae52e2e498625e86b
MD5 1d46e257d96c05425584db519b8ee684
BLAKE2b-256 edc9768ef4a8b17dd788379769f07fb699b484c7b659fa192d1b3ee393d31477

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page