tritlib 2.0.1__tar.gz → 2.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of tritlib might be problematic. Click here for more details.
- tritlib-2.1.0/.claude/settings.local.json +9 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/CHANGELOG.md +120 -3
- {tritlib-2.0.1 → tritlib-2.1.0}/CLAUDE.md +10 -1
- {tritlib-2.0.1 → tritlib-2.1.0}/PKG-INFO +10 -9
- {tritlib-2.0.1 → tritlib-2.1.0}/README.md +9 -8
- {tritlib-2.0.1 → tritlib-2.1.0}/pyproject.toml +1 -1
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/logic/base.py +10 -9
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/logic/bochvar.py +3 -2
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/logic/plural.py +5 -6
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/tfloat.py +45 -16
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/trit.py +13 -4
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/tritarray.py +89 -55
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/trits.py +35 -21
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/trybble.py +1 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/tryte.py +1 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/word.py +1 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_tfloat_add.py +24 -6
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_tritarray.py +3 -3
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_trits.py +1 -1
- {tritlib-2.0.1 → tritlib-2.1.0}/.gitignore +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/LICENSE +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/py.typed +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/__init__.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/context.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/logic/__init__.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/logic/heyting.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/logic/kleene.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/logic/lukasiewicz.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/src/tritlib/logic/rm3.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_context.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_logic.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_logic_kleene.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_plural.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_tfloat.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_tfloat_div.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_tfloat_mul.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_trit.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_tryte.py +0 -0
- {tritlib-2.0.1 → tritlib-2.1.0}/tests/test_word.py +0 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{
|
|
2
|
+
"permissions": {
|
|
3
|
+
"allow": [
|
|
4
|
+
"Bash(python -)",
|
|
5
|
+
"Bash(timeout 400 /home/newick/Programmes/setnex/tritlib/.venv/bin/python -m pytest test_regressions.py -q -p no:cacheprovider --timeout=60)",
|
|
6
|
+
"Bash(timeout 400 /home/newick/Programmes/setnex/tritlib/.venv/bin/python -m pytest test_regressions.py -q -p no:cacheprovider -k \"not full_width and not remainder_is_reduced\")"
|
|
7
|
+
]
|
|
8
|
+
}
|
|
9
|
+
}
|
|
@@ -4,9 +4,112 @@ All notable changes to this project will be documented in this file.
|
|
|
4
4
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
+
## [2.1.0] — 2026-07-21
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- `TritArray.__divmod__` returned an unreduced remainder whenever the
|
|
12
|
+
divisor exceeded roughly a third of the width's range (about 29 % of
|
|
13
|
+
random operand pairs at width 9). The quotient decision and the final
|
|
14
|
+
correction loop compared `V + V` at the operand width, which wrapped
|
|
15
|
+
silently. `divmod(TritArray(7872, 9), TritArray(-7887, 9))` gave
|
|
16
|
+
`(0, 7872)` instead of `(-1, -15)`. The identity `a == b·q + r` held
|
|
17
|
+
throughout, which is why the tests never caught it.
|
|
18
|
+
- `TritArray.__divmod__` now delegates to `Trits.__divmod__` instead of
|
|
19
|
+
duplicating the algorithm at fixed width. Division must run at
|
|
20
|
+
arbitrary precision: the intermediate partial remainder reaches
|
|
21
|
+
`1.5 × |divisor|`.
|
|
22
|
+
- `Trits.__divmod__` chose each quotient trit from the sign of the
|
|
23
|
+
leading trit alone, so the partial remainder doubled at every step
|
|
24
|
+
and the one-unit-at-a-time correction loop had to run an
|
|
25
|
+
astronomical number of iterations (a 52-trit division drifted to
|
|
26
|
+
`4·10²² × |d|`). The decision is now made on magnitude, restoring the
|
|
27
|
+
`|pr| ≤ |d| / 2` invariant.
|
|
28
|
+
- `Trits.__divmod__` dropped the `len(self) < len(other)` shortcut,
|
|
29
|
+
which returned an unreduced remainder and amounted to a second
|
|
30
|
+
remainder convention inside the same function: `divmod(34, 58)` gave
|
|
31
|
+
`(0, 34)` instead of `(1, -24)`.
|
|
32
|
+
- `TritArray.__eq__` and `__lt__` raised `TypeError` on any non-
|
|
33
|
+
`TritArray` operand instead of returning `NotImplemented`, so
|
|
34
|
+
`array == 5`, `array == None` and `array in [1, 2]` all blew up.
|
|
35
|
+
- `TritArray.__eq__` also raised `ValueError` when the widths differed,
|
|
36
|
+
which propagated through every implicit comparison Python performs:
|
|
37
|
+
`Tryte(1) in [Word(1)]`, `[Tryte(1)] == [Word(1)]`, `list.index`,
|
|
38
|
+
`!=`, and — via `@total_ordering` — `<=`, `>` and `>=`. Mismatched
|
|
39
|
+
widths now compare unequal (`False`), matching `TFloat`. `__lt__`
|
|
40
|
+
returns `NotImplemented`, so ordering across widths raises the
|
|
41
|
+
standard `TypeError` instead.
|
|
42
|
+
- `Trybble`, `Tryte` and `Word` declared no `__slots__`, so every
|
|
43
|
+
instance carried a `__dict__` despite `TritArray` defining slots.
|
|
44
|
+
They now declare `__slots__ = ()`; declaring the inherited names
|
|
45
|
+
again would allocate a second, shadowing slot per attribute (a
|
|
46
|
+
`Tryte` measured 64 bytes against 48 for a `TritArray`).
|
|
47
|
+
- `TritArray.set` accepted any object as the replacement trit. The
|
|
48
|
+
invalid instance was built silently and only failed later, in
|
|
49
|
+
`__str__`, as a confusing `KeyError`. It now rejects non-`Trit`
|
|
50
|
+
values on the spot.
|
|
51
|
+
- `cons` and `acons` accepted operands of a different width and
|
|
52
|
+
silently truncated through `zip`, unlike every other binary
|
|
53
|
+
operation. They now raise `TypeError`.
|
|
54
|
+
- `rotate_left` and `rotate_right` were wrong for `n > width`:
|
|
55
|
+
`Tryte(42).rotate_left(10)` did not equal `rotate_left(1)`. The
|
|
56
|
+
count is now taken modulo the width.
|
|
57
|
+
- `__lshift__` and `__rshift__` accepted negative counts and did
|
|
58
|
+
something arbitrary rather than failing: `n = -1` made the slice
|
|
59
|
+
count from the end, moving the most significant trit into the least
|
|
60
|
+
significant position and zeroing the rest, while `[Z] * -1` silently
|
|
61
|
+
produced an empty list. Below `-width` the value came back
|
|
62
|
+
unchanged. Both now raise `ValueError`, as Python's own integers do.
|
|
63
|
+
- `Trit(True)` was accepted and stored `True` as the trit value, since
|
|
64
|
+
`bool` is a subclass of `int`.
|
|
65
|
+
- `TFloat.__neg__` mapped the all-P pattern to the all-N one, turning
|
|
66
|
+
∞ into NaR and NaR into ∞. Since `__sub__` is `self + (-other)`,
|
|
67
|
+
`x - ∞` returned NaR and `x - NaR` returned ∞. Both special values
|
|
68
|
+
are now fixed points under negation, which also matches the
|
|
69
|
+
constructor, where `TFloat(float("-inf"), w)` already encodes ∞.
|
|
70
|
+
- All errors now have a meaningful message.
|
|
71
|
+
|
|
72
|
+
### Changed
|
|
73
|
+
|
|
74
|
+
- `tfloat.py`, `logic/base.py`, `logic/bochvar.py` and `logic/plural.py`
|
|
75
|
+
imported names from the `tritlib` package itself rather than from the
|
|
76
|
+
defining modules. That only worked because `__init__.py` happened to
|
|
77
|
+
import `trit`, `trits` and `tritarray` before `word` (which pulls in
|
|
78
|
+
`tfloat`): reordering two lines of `__init__.py` broke the package
|
|
79
|
+
with `ImportError: cannot import name 'TritArray'`. All four now
|
|
80
|
+
import the concrete modules, and the package no longer depends on the
|
|
81
|
+
order of its own imports.
|
|
82
|
+
- `TFloat.__add__`: `∞ + ∞` is now NaR rather than ∞. Tekum has a
|
|
83
|
+
single unsigned ∞, so `-∞ = ∞` and `∞ + ∞` is the same expression as
|
|
84
|
+
`∞ - ∞` — it cannot resolve to ∞. The IEEE rule `+∞ + +∞ = +∞`
|
|
85
|
+
depends on the sign being carried by the value. `∞ × ∞` is
|
|
86
|
+
unaffected and stays ∞.
|
|
87
|
+
|
|
88
|
+
### Documentation
|
|
89
|
+
|
|
90
|
+
- The division docstrings described the opposite of what the code did
|
|
91
|
+
(« no magnitude comparison is needed ») and claimed the remainder
|
|
92
|
+
carried the sign of the dividend; it is balanced, so it takes
|
|
93
|
+
whichever sign minimises `|r|` — `divmod(Trits(-200), Trits(-57))`
|
|
94
|
+
is `(4, 28)`.
|
|
95
|
+
- Corrected the worked examples: `Trits(42)` is `"+---0"`, and
|
|
96
|
+
`"+-0+"` is 19, not 8 (both in `Trits` and `TritArray`).
|
|
97
|
+
- README: B3 is the internal (weak) Bochvar system, where Z is
|
|
98
|
+
absorbing — `Z ∧ Z = Z`, not `N`; the requirement is Python ≥ 3.11,
|
|
99
|
+
matching `pyproject.toml`; the `divmod` example showed a result that
|
|
100
|
+
no version of the code ever produced.
|
|
101
|
+
- `TFloat.__neg__` and `__add__` document the single unsigned ∞ and
|
|
102
|
+
why `∞ + ∞` cannot be ∞.
|
|
103
|
+
- `TFloat.__lt__` states the Tekum ordering explicitly: NaR sorts below
|
|
104
|
+
every finite value and ∞ above them, so the special values take part
|
|
105
|
+
in comparisons rather than poisoning them the way IEEE NaN does.
|
|
106
|
+
- The docstrings of `set`, `cons`, `acons`, the shifts and the
|
|
107
|
+
rotations describe the guards added above.
|
|
108
|
+
|
|
7
109
|
## [2.0.0] — 2026-05-18
|
|
8
110
|
|
|
9
111
|
### Breaking
|
|
112
|
+
|
|
10
113
|
- `Tryte` is now a fixed-width 9-trit type (T9), aligned with Setnex ISA v0.8.
|
|
11
114
|
Its constructor no longer accepts a `width` argument. Code that did
|
|
12
115
|
`Tryte(value, w)` for `w ≠ 9` must migrate to `TritArray(value, w)`.
|
|
@@ -17,6 +120,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
17
120
|
width-locked subclasses.
|
|
18
121
|
|
|
19
122
|
### Added
|
|
123
|
+
|
|
20
124
|
- `TritArray(value, width)` — arbitrary-width balanced ternary word (the
|
|
21
125
|
generic base type).
|
|
22
126
|
- `Trybble(value)` — 3-trit field (T3), the smallest addressable grouping
|
|
@@ -30,6 +134,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
30
134
|
semantics (overflow at ±9841, fixed `len() == 9`, etc.).
|
|
31
135
|
|
|
32
136
|
### Changed
|
|
137
|
+
|
|
33
138
|
- All internal `TFloat` arithmetic (mantissa, regime, exponent, work-scale
|
|
34
139
|
bounds, double-width products, division work widths) routes through
|
|
35
140
|
`TritArray`. `TFloat._raw` is a `TritArray` of even width ≥ 8; the
|
|
@@ -42,6 +147,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
42
147
|
## [1.3.0] — 2026-04-29
|
|
43
148
|
|
|
44
149
|
### Added
|
|
150
|
+
|
|
45
151
|
- Native trit-level division on `TFloat` (Tekum arithmetic)
|
|
46
152
|
- Mantissa division at a working scale `p_work = max(p_self, p_other) + 2`
|
|
47
153
|
- Numerator pre-shifted by `3^p_work` to recover the fractional quotient as an integer
|
|
@@ -49,6 +155,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
49
155
|
- Result re-encoded by `_finalize`; no longer routes through Python `float`
|
|
50
156
|
|
|
51
157
|
### Fixed
|
|
158
|
+
|
|
52
159
|
- `Trits.__divmod__` and `Tryte.__divmod__` exponential drift on certain operand magnitudes.
|
|
53
160
|
Initial `partial_rest = s[:len(d)-1]` could already exceed `|d|/2` when `|d|` sat at the
|
|
54
161
|
lower end of its trit-length range, breaking the single-trit quotient invariant; the
|
|
@@ -60,6 +167,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
60
167
|
values near `3²⁶/2`). The decision now uses an `int` comparison, immune to truncation.
|
|
61
168
|
|
|
62
169
|
### Changed
|
|
170
|
+
|
|
63
171
|
- `TFloat._from_float` (renamed from `from_float`): privatized; bounded fraction
|
|
64
172
|
quantification with `_find_regime` recomputed in-loop, plus a final clamp
|
|
65
173
|
- `_finalize` factored out of `__add__`, `__mul__`, and `__truediv__` for shared
|
|
@@ -72,20 +180,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
72
180
|
edge cases, plus explicit overflow guard when `e ≥ width`
|
|
73
181
|
|
|
74
182
|
## [1.2.3] — 2026-04-22
|
|
183
|
+
|
|
75
184
|
- added TFloat conversion from and into int/Tryte/Trits
|
|
76
185
|
- renamed to_tryte into to_raw
|
|
77
186
|
|
|
78
187
|
## [1.2.2] — 2026-04-05
|
|
79
|
-
- Updated README.md and pyproject.toml
|
|
80
188
|
|
|
189
|
+
- Updated README.md and pyproject.toml
|
|
81
190
|
|
|
82
191
|
## [1.2.1] — 2026-04-05
|
|
83
|
-
- Symmetric Euclidean `__divmod__` implementation
|
|
84
192
|
|
|
193
|
+
- Symmetric Euclidean `__divmod__` implementation
|
|
85
194
|
|
|
86
195
|
## [1.2.0] — 2026-04-05
|
|
87
196
|
|
|
88
197
|
### Added
|
|
198
|
+
|
|
89
199
|
- Native trit-level multiplication on `TFloat` (Tekum arithmetic)
|
|
90
200
|
- Double-width Tryte arithmetic for the product
|
|
91
201
|
- Exponent addition, scale reduction via ternary shift
|
|
@@ -94,6 +204,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
94
204
|
## [1.1.0] — 2026-04-05
|
|
95
205
|
|
|
96
206
|
### Added
|
|
207
|
+
|
|
97
208
|
- Native trit-level addition on `TFloat` (Tekum arithmetic)
|
|
98
209
|
- Direct manipulation of extended mantissas via `Tryte` operations
|
|
99
210
|
- Exponent alignment via ternary shift
|
|
@@ -104,10 +215,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
104
215
|
## [1.0.0] — 2026-04-04
|
|
105
216
|
|
|
106
217
|
### Changed
|
|
218
|
+
|
|
107
219
|
- API declared stable
|
|
108
220
|
- Version bumped to 1.0.0 — no breaking changes from 0.7.0
|
|
109
221
|
|
|
110
222
|
### Added
|
|
223
|
+
|
|
111
224
|
- `py.typed` marker for mypy support
|
|
112
225
|
- CHANGELOG.md
|
|
113
226
|
- 99% test coverage
|
|
@@ -115,6 +228,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
115
228
|
## [0.7.0] — 2026-04-04
|
|
116
229
|
|
|
117
230
|
### Added
|
|
231
|
+
|
|
118
232
|
- `TFloat` — Tekum tapered precision floating-point type (arXiv:2512.10964)
|
|
119
233
|
- Decode from `Tryte` and encode from Python `float`
|
|
120
234
|
- Arithmetic via float conversion (`+`, `-`, `*`, `/`)
|
|
@@ -130,11 +244,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
130
244
|
- This CHANGELOG
|
|
131
245
|
|
|
132
246
|
### Changed
|
|
247
|
+
|
|
133
248
|
- `Trit.__and__`, `__or__`, `__invert__` now dispatch via active logic system (Kleene by default, fast path when no context manager is active)
|
|
134
249
|
|
|
135
250
|
## [0.2.0] — 2026-04-03
|
|
136
251
|
|
|
137
252
|
### Added
|
|
253
|
+
|
|
138
254
|
- `Tryte` — fixed-width ternary word type
|
|
139
255
|
- Three addition modes: truncating, with carry, saturating
|
|
140
256
|
- Shifts (`<<`, `>>`) and rotations (`rotate_left`, `rotate_right`)
|
|
@@ -151,12 +267,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
151
267
|
- `Trit.cons` and `Trit.acons` operators
|
|
152
268
|
|
|
153
269
|
### Changed
|
|
270
|
+
|
|
154
271
|
- `Trits` internal storage changed to tuple (immutable)
|
|
155
272
|
- `Trits._from_trits` centralizes normalization and construction
|
|
156
273
|
|
|
157
274
|
## [0.1.0] — 2026-04-02
|
|
158
275
|
|
|
159
276
|
### Added
|
|
277
|
+
|
|
160
278
|
- `Trit` — immutable single balanced ternary digit
|
|
161
279
|
- Construction from int with validation
|
|
162
280
|
- Negation, multiplication
|
|
@@ -173,7 +291,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
173
291
|
- MIT license
|
|
174
292
|
- Initial README
|
|
175
293
|
|
|
176
|
-
[Unreleased]: https://codeberg.org/newick_2/tritlib/compare/v0.7.0...HEAD
|
|
177
294
|
[0.7.0]: https://codeberg.org/newick_2/tritlib/compare/v0.2.0...v0.7.0
|
|
178
295
|
[0.2.0]: https://codeberg.org/newick_2/tritlib/compare/v0.1.0...v0.2.0
|
|
179
296
|
[0.1.0]: https://codeberg.org/newick_2/tritlib/releases/tag/v0.1.0
|
|
@@ -58,7 +58,16 @@ When touching `TFloat`:
|
|
|
58
58
|
|
|
59
59
|
### Division pitfalls (Trits / TritArray)
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
There is exactly **one** division algorithm, in `Trits.__divmod__`. `TritArray.__divmod__` converts both operands with `to_trits()`, divides there, and packs the results back at the operand width (both always fit, so nothing is truncated). Do not reintroduce a second, fixed-width implementation: the partial remainder reaches `1.5 × |d|` mid-loop, so a `TritArray` comparison at the operand width wraps silently and returns an unreduced remainder — the identity `a == b·q + r` still holds, which is why it hid behind the tests for so long.
|
|
62
|
+
|
|
63
|
+
Two things in `Trits.__divmod__` are load-bearing:
|
|
64
|
+
|
|
65
|
+
- **The quotient trit is chosen by magnitude**, comparing `V + V` against `±|d|` where `V` is the partial remainder scaled by 3 plus the next dividend trit. This maintains `|pr| ≤ |d|/2` at every step. Deciding on the sign of the leading trit alone (the earlier code) doubles the partial remainder at each step; the final correction loop, which adjusts by one unit at a time, then needs an astronomical number of iterations — a 52-trit division drifted to `4·10²² × |d|` and never terminated in practice.
|
|
66
|
+
- **Every trit of the dividend is consumed**, starting from `partial_rest = []`. Do not "optimise" back either the `partial_rest = s[:len(d)-1]` pre-load or the `if len(self) < len(other): return Trits(0), self` shortcut; the latter returned an unreduced remainder (`34 / 58` gave `(0, 34)` instead of `(1, −24)`), i.e. a second remainder convention inside the same function.
|
|
67
|
+
|
|
68
|
+
Remainder semantics are symmetric/balanced: `|r| ≤ |b|/2`, so the remainder takes whichever sign minimises its magnitude — **not** the sign of the dividend (`divmod(Trits(-200), Trits(-57)) == (Trits(4), Trits(28))`).
|
|
69
|
+
|
|
70
|
+
Any test touching division must assert `2·|r| ≤ |b|` alongside `b·q + r == a`. The identity alone passes even when the algorithm is broken.
|
|
62
71
|
|
|
63
72
|
## Conventions to follow
|
|
64
73
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tritlib
|
|
3
|
-
Version: 2.0
|
|
3
|
+
Version: 2.1.0
|
|
4
4
|
Summary: Balanced ternary arithmetic and multi-valued logic library
|
|
5
5
|
Project-URL: Homepage, https://codeberg.org/setnex-org/tritlib
|
|
6
6
|
Project-URL: Repository, https://codeberg.org/setnex-org/tritlib
|
|
@@ -47,7 +47,7 @@ Five ternary logic systems, selectable at runtime via a common abstract interfac
|
|
|
47
47
|
| **Kleene (K3)** | Unknown (epistemic) | Default. AND = min, OR = max |
|
|
48
48
|
| **Łukasiewicz (L3)** | Indeterminate (ontological) | Z → Z yields P (tautological self-implication) |
|
|
49
49
|
| **Heyting (HT)** | Non-proved (constructivist) | ~Z = N (unproved is false) |
|
|
50
|
-
| **B3 (Bochvar)** |
|
|
50
|
+
| **B3 (Bochvar)** | Meaningless (infectious) | Z is absorbing: Z ∧ Z = Z ∨ Z = Z → Z = Z |
|
|
51
51
|
| **RM3 (R-mingle)** | Relevant entailment | Restricted implication |
|
|
52
52
|
|
|
53
53
|
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.
|
|
@@ -71,7 +71,7 @@ tritlib provides the building blocks for balanced ternary processor simulation:
|
|
|
71
71
|
pip install tritlib
|
|
72
72
|
```
|
|
73
73
|
|
|
74
|
-
Requires Python ≥ 3.
|
|
74
|
+
Requires Python ≥ 3.11. No external dependencies.
|
|
75
75
|
|
|
76
76
|
## Usage
|
|
77
77
|
|
|
@@ -105,11 +105,12 @@ print(int(a * b)) # 798
|
|
|
105
105
|
q, r = divmod(Trits(13), Trits(4))
|
|
106
106
|
assert int(q) * 4 + int(r) == 13
|
|
107
107
|
|
|
108
|
-
#
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
print(int(
|
|
108
|
+
# The remainder is balanced: |r| <= |divisor| / 2, so it takes
|
|
109
|
+
# whichever sign minimises its magnitude — not the dividend's.
|
|
110
|
+
q, r = divmod(Trits(40), Trits(6))
|
|
111
|
+
assert int(q) * 6 + int(r) == 40
|
|
112
|
+
print(int(q)) # 7
|
|
113
|
+
print(int(r)) # -2
|
|
113
114
|
```
|
|
114
115
|
|
|
115
116
|
### Fixed-width words
|
|
@@ -201,7 +202,7 @@ from tritlib.logic.plural import pluralize
|
|
|
201
202
|
# Evaluate Z → Z across all five logic systems
|
|
202
203
|
result = pluralize(lambda a, b: a.imply(b), Z, Z)
|
|
203
204
|
print(result.divergent) # True — logics disagree
|
|
204
|
-
print(result.groups) # {
|
|
205
|
+
print(result.groups) # {Trit(0): ['BI3', 'K3', 'RM3'], Trit(1): ['HT', 'L3']}
|
|
205
206
|
print(result.consensus) # None — no unanimous agreement
|
|
206
207
|
```
|
|
207
208
|
|
|
@@ -25,7 +25,7 @@ Five ternary logic systems, selectable at runtime via a common abstract interfac
|
|
|
25
25
|
| **Kleene (K3)** | Unknown (epistemic) | Default. AND = min, OR = max |
|
|
26
26
|
| **Łukasiewicz (L3)** | Indeterminate (ontological) | Z → Z yields P (tautological self-implication) |
|
|
27
27
|
| **Heyting (HT)** | Non-proved (constructivist) | ~Z = N (unproved is false) |
|
|
28
|
-
| **B3 (Bochvar)** |
|
|
28
|
+
| **B3 (Bochvar)** | Meaningless (infectious) | Z is absorbing: Z ∧ Z = Z ∨ Z = Z → Z = Z |
|
|
29
29
|
| **RM3 (R-mingle)** | Relevant entailment | Restricted implication |
|
|
30
30
|
|
|
31
31
|
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.
|
|
@@ -49,7 +49,7 @@ tritlib provides the building blocks for balanced ternary processor simulation:
|
|
|
49
49
|
pip install tritlib
|
|
50
50
|
```
|
|
51
51
|
|
|
52
|
-
Requires Python ≥ 3.
|
|
52
|
+
Requires Python ≥ 3.11. No external dependencies.
|
|
53
53
|
|
|
54
54
|
## Usage
|
|
55
55
|
|
|
@@ -83,11 +83,12 @@ print(int(a * b)) # 798
|
|
|
83
83
|
q, r = divmod(Trits(13), Trits(4))
|
|
84
84
|
assert int(q) * 4 + int(r) == 13
|
|
85
85
|
|
|
86
|
-
#
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
print(int(
|
|
86
|
+
# The remainder is balanced: |r| <= |divisor| / 2, so it takes
|
|
87
|
+
# whichever sign minimises its magnitude — not the dividend's.
|
|
88
|
+
q, r = divmod(Trits(40), Trits(6))
|
|
89
|
+
assert int(q) * 6 + int(r) == 40
|
|
90
|
+
print(int(q)) # 7
|
|
91
|
+
print(int(r)) # -2
|
|
91
92
|
```
|
|
92
93
|
|
|
93
94
|
### Fixed-width words
|
|
@@ -179,7 +180,7 @@ from tritlib.logic.plural import pluralize
|
|
|
179
180
|
# Evaluate Z → Z across all five logic systems
|
|
180
181
|
result = pluralize(lambda a, b: a.imply(b), Z, Z)
|
|
181
182
|
print(result.divergent) # True — logics disagree
|
|
182
|
-
print(result.groups) # {
|
|
183
|
+
print(result.groups) # {Trit(0): ['BI3', 'K3', 'RM3'], Trit(1): ['HT', 'L3']}
|
|
183
184
|
print(result.consensus) # None — no unanimous agreement
|
|
184
185
|
```
|
|
185
186
|
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
from abc import ABC, abstractmethod
|
|
2
|
-
from tritlib import Trit
|
|
2
|
+
from tritlib.trit import Trit
|
|
3
|
+
|
|
4
|
+
|
|
3
5
|
class TernaryLogic(ABC):
|
|
4
6
|
"""
|
|
5
7
|
Abstract base class for ternary logic operations.
|
|
@@ -14,23 +16,22 @@ class TernaryLogic(ABC):
|
|
|
14
16
|
xor_op(a,b): Returns the logical XOR of two trits.
|
|
15
17
|
"""
|
|
16
18
|
|
|
17
|
-
def not_op(self, a: Trit) -> Trit:
|
|
19
|
+
def not_op(self, a: Trit) -> Trit:
|
|
18
20
|
return Trit(-a.value)
|
|
19
21
|
|
|
20
|
-
def and_op(self, a: Trit, b: Trit) -> Trit:
|
|
22
|
+
def and_op(self, a: Trit, b: Trit) -> Trit:
|
|
21
23
|
return Trit(min(b.value, a.value))
|
|
22
|
-
|
|
23
|
-
def or_op(self, a: Trit, b: Trit) -> Trit:
|
|
24
|
-
return Trit(max(a.value,b.value))
|
|
24
|
+
|
|
25
|
+
def or_op(self, a: Trit, b: Trit) -> Trit:
|
|
26
|
+
return Trit(max(a.value, b.value))
|
|
25
27
|
|
|
26
28
|
@abstractmethod
|
|
27
29
|
def imply_op(self, a: Trit, b: Trit) -> Trit: ...
|
|
28
30
|
|
|
29
31
|
def xor_op(self, a: Trit, b: Trit) -> Trit:
|
|
30
32
|
return self.or_op(
|
|
31
|
-
self.and_op(a, self.not_op(b)),
|
|
32
|
-
self.and_op(self.not_op(a), b)
|
|
33
|
+
self.and_op(a, self.not_op(b)), self.and_op(self.not_op(a), b)
|
|
33
34
|
)
|
|
34
35
|
|
|
35
36
|
def equiv_op(self, a: Trit, b: Trit) -> Trit:
|
|
36
|
-
return self.not_op(self.xor_op(a,b))
|
|
37
|
+
return self.not_op(self.xor_op(a, b))
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
from tritlib.logic.base import TernaryLogic
|
|
2
|
-
from tritlib import N, P,Z, Trit
|
|
2
|
+
from tritlib.trit import N, P, Z, Trit
|
|
3
|
+
|
|
3
4
|
|
|
4
5
|
class Bochvar(TernaryLogic):
|
|
5
6
|
"""
|
|
@@ -11,6 +12,7 @@ class Bochvar(TernaryLogic):
|
|
|
11
12
|
or_op(a, b): Returns the Bochvar logical OR of two trits.
|
|
12
13
|
imply_op(a, b): Returns the Bochvar logical implication of two trits.
|
|
13
14
|
"""
|
|
15
|
+
|
|
14
16
|
def and_op(self, a: Trit, b: Trit) -> Trit:
|
|
15
17
|
if a == Z or b == Z:
|
|
16
18
|
return Z
|
|
@@ -32,4 +34,3 @@ class Bochvar(TernaryLogic):
|
|
|
32
34
|
if a == b == N:
|
|
33
35
|
return N
|
|
34
36
|
return P
|
|
35
|
-
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
from collections import Counter
|
|
2
|
-
from tritlib import Trit
|
|
2
|
+
from tritlib.trit import Trit
|
|
3
3
|
from dataclasses import dataclass
|
|
4
4
|
from .bochvar import Bochvar as BI3
|
|
5
5
|
from .kleene import Kleene as K3
|
|
@@ -11,7 +11,7 @@ from tritlib.context import logic_mode
|
|
|
11
11
|
|
|
12
12
|
@dataclass(frozen=True)
|
|
13
13
|
class PluralResult:
|
|
14
|
-
results: dict[str, Trit]
|
|
14
|
+
results: dict[str, Trit]
|
|
15
15
|
|
|
16
16
|
@property
|
|
17
17
|
def _to_list(self):
|
|
@@ -39,9 +39,8 @@ class PluralResult:
|
|
|
39
39
|
majority_value = counts.most_common(1)[0][0]
|
|
40
40
|
return set([k for k, v in self.results.items() if v != majority_value])
|
|
41
41
|
|
|
42
|
-
|
|
43
42
|
@property
|
|
44
|
-
def groups(self) -> dict[str,list[Trit]]:
|
|
43
|
+
def groups(self) -> dict[str, list[Trit]]:
|
|
45
44
|
res = dict()
|
|
46
45
|
for t in set(self._to_list):
|
|
47
46
|
res[t] = [k for k, v in self.results.items() if v == t]
|
|
@@ -49,9 +48,9 @@ class PluralResult:
|
|
|
49
48
|
|
|
50
49
|
|
|
51
50
|
def pluralize(f, *args) -> PluralResult:
|
|
52
|
-
logics = {
|
|
51
|
+
logics = {"BI3": BI3, "HT": HT, "K3": K3, "L3": L3, "RM3": RM3}
|
|
53
52
|
res = dict()
|
|
54
|
-
for k,v in logics.items():
|
|
53
|
+
for k, v in logics.items():
|
|
55
54
|
with logic_mode(v):
|
|
56
55
|
res[k] = f(*args)
|
|
57
56
|
return PluralResult(res)
|
|
@@ -25,7 +25,9 @@ from __future__ import annotations
|
|
|
25
25
|
from functools import total_ordering
|
|
26
26
|
from math import floor, log, isnan, isinf
|
|
27
27
|
from typing import Optional
|
|
28
|
-
from
|
|
28
|
+
from .trit import Z, N, P, Trit
|
|
29
|
+
from .tritarray import TritArray
|
|
30
|
+
from .trits import Trits
|
|
29
31
|
|
|
30
32
|
BIAS = [0, 1, 2, 4, 10, 28, 82, 244]
|
|
31
33
|
"""Exponent bias table indexed by |regime|.
|
|
@@ -60,7 +62,7 @@ class TFloat:
|
|
|
60
62
|
>>> TFloat(TritArray(1640, 8)) # decode: θ = 1.0
|
|
61
63
|
TFloat(1.0, width=8)
|
|
62
64
|
>>> TFloat(3.14, width=20) # encode
|
|
63
|
-
TFloat(3.
|
|
65
|
+
TFloat(3.140000001393834, width=20)
|
|
64
66
|
>>> float(TFloat(1.0, width=8))
|
|
65
67
|
1.0
|
|
66
68
|
"""
|
|
@@ -98,7 +100,7 @@ class TFloat:
|
|
|
98
100
|
raise ValueError("width required for float construction")
|
|
99
101
|
self._from_float(v, width)
|
|
100
102
|
else:
|
|
101
|
-
raise TypeError
|
|
103
|
+
raise TypeError(f"expected TritArray, int or float, got {type(v).__name__}")
|
|
102
104
|
|
|
103
105
|
# ── Construction ────────────────────────────────────────────────
|
|
104
106
|
|
|
@@ -430,9 +432,9 @@ class TFloat:
|
|
|
430
432
|
case "zero":
|
|
431
433
|
return Trits(0)
|
|
432
434
|
case "nar":
|
|
433
|
-
raise ValueError
|
|
435
|
+
raise ValueError("cannot convert NaR to an integer")
|
|
434
436
|
case "inf":
|
|
435
|
-
raise OverflowError
|
|
437
|
+
raise OverflowError("cannot convert infinity to an integer")
|
|
436
438
|
e = self.exponent_value
|
|
437
439
|
if e < 0:
|
|
438
440
|
return Trits(0)
|
|
@@ -476,13 +478,13 @@ class TFloat:
|
|
|
476
478
|
case "zero":
|
|
477
479
|
return TritArray(0, width)
|
|
478
480
|
case "nar":
|
|
479
|
-
raise ValueError
|
|
481
|
+
raise ValueError("cannot convert NaR to an integer")
|
|
480
482
|
case "inf":
|
|
481
|
-
raise OverflowError
|
|
483
|
+
raise OverflowError("cannot convert infinity to an integer")
|
|
482
484
|
p = self.fraction_trit_count
|
|
483
485
|
e = self.exponent_value
|
|
484
486
|
if e >= width:
|
|
485
|
-
raise OverflowError
|
|
487
|
+
raise OverflowError(f"exponent {e} does not fit in {width} trits")
|
|
486
488
|
if e < 0:
|
|
487
489
|
return TritArray(0, width)
|
|
488
490
|
n = min(e, p)
|
|
@@ -686,9 +688,11 @@ class TFloat:
|
|
|
686
688
|
Tekum monotonicity (Proposition 4) guarantees that integer
|
|
687
689
|
ordering on the raw TritArray corresponds to numerical ordering
|
|
688
690
|
of the represented values.
|
|
691
|
+
|
|
692
|
+
According to Tekum, NaR < any float < inf
|
|
689
693
|
"""
|
|
690
694
|
if not isinstance(other, TFloat):
|
|
691
|
-
raise TypeError
|
|
695
|
+
raise TypeError(f"expected TFloat, got {type(other).__name__}")
|
|
692
696
|
if self.width != other.width:
|
|
693
697
|
return NotImplemented
|
|
694
698
|
return self._raw < other._raw
|
|
@@ -696,8 +700,23 @@ class TFloat:
|
|
|
696
700
|
def __neg__(self) -> TFloat:
|
|
697
701
|
"""Negate by inverting all trits of the raw TritArray.
|
|
698
702
|
|
|
699
|
-
Proposition 3 of the Tekum paper guarantees θ(-t) = -θ(t)
|
|
703
|
+
Proposition 3 of the Tekum paper guarantees θ(-t) = -θ(t) for
|
|
704
|
+
ordinary values.
|
|
705
|
+
|
|
706
|
+
The two non-zero special values are fixed points instead, and
|
|
707
|
+
are returned unchanged. Tekum has a single, unsigned ∞, so
|
|
708
|
+
-∞ = ∞; inverting its all-P pattern would otherwise land on
|
|
709
|
+
the all-N pattern, i.e. turn ∞ into NaR (and NaR into ∞).
|
|
710
|
+
The constructor already agrees: ``TFloat(float("-inf"), w)``
|
|
711
|
+
encodes ∞. Zero is its own negation anyway, its raw being
|
|
712
|
+
all-Z.
|
|
713
|
+
|
|
714
|
+
Note that this makes ``x - ∞`` equal ∞ rather than NaR, and
|
|
715
|
+
``∞ - ∞`` the same expression as ``∞ + ∞`` — see ``__add__``,
|
|
716
|
+
which resolves it to NaR.
|
|
700
717
|
"""
|
|
718
|
+
if self._special == "nar" or self._special == "inf":
|
|
719
|
+
return self
|
|
701
720
|
return TFloat(-self._raw)
|
|
702
721
|
|
|
703
722
|
# ── Native Arithmetic ────────────────────────────────────────────
|
|
@@ -712,14 +731,14 @@ class TFloat:
|
|
|
712
731
|
TypeError: If widths differ.
|
|
713
732
|
"""
|
|
714
733
|
if not isinstance(other, TFloat):
|
|
715
|
-
raise TypeError
|
|
734
|
+
raise TypeError(f"expected TFloat, got {type(other).__name__}")
|
|
716
735
|
if self.width != other.width:
|
|
717
736
|
return NotImplemented
|
|
718
737
|
return self + (-other)
|
|
719
738
|
|
|
720
739
|
def __truediv__(self, other) -> TFloat:
|
|
721
740
|
if not isinstance(other, TFloat):
|
|
722
|
-
raise TypeError
|
|
741
|
+
raise TypeError(f"expected TFloat, got {type(other).__name__}")
|
|
723
742
|
if self.width != other.width:
|
|
724
743
|
return NotImplemented
|
|
725
744
|
if self._special == "nar" or other._special == "nar":
|
|
@@ -773,11 +792,19 @@ class TFloat:
|
|
|
773
792
|
the two are summed as TritArray. The result is normalised and
|
|
774
793
|
re-encoded by ``_finalize``.
|
|
775
794
|
|
|
776
|
-
Special-value handling:
|
|
795
|
+
Special-value handling (wheel-algebra semantics):
|
|
777
796
|
- any operand is NaR → NaR
|
|
778
|
-
-
|
|
797
|
+
- both operands are inf → NaR
|
|
798
|
+
- exactly one operand is inf → inf
|
|
779
799
|
- any operand is zero → returns the other operand
|
|
780
800
|
|
|
801
|
+
``∞ + ∞`` is indeterminate, not ∞: Tekum has a single,
|
|
802
|
+
unsigned ∞ (so ``-∞ = ∞``, see ``__neg__``), which makes
|
|
803
|
+
``∞ + ∞`` and ``∞ - ∞`` the very same expression. The IEEE
|
|
804
|
+
rule ``+∞ + +∞ = +∞`` relies on the sign being carried by the
|
|
805
|
+
value, which is not the case here. Multiplication is not
|
|
806
|
+
affected by that indeterminacy and keeps ``∞ × ∞ = ∞``.
|
|
807
|
+
|
|
781
808
|
Args:
|
|
782
809
|
other: Another TFloat of the same width.
|
|
783
810
|
|
|
@@ -789,13 +816,15 @@ class TFloat:
|
|
|
789
816
|
NotImplemented: If widths differ.
|
|
790
817
|
"""
|
|
791
818
|
if not isinstance(other, TFloat):
|
|
792
|
-
raise TypeError
|
|
819
|
+
raise TypeError(f"expected TFloat, got {type(other).__name__}")
|
|
793
820
|
if self.width != other.width:
|
|
794
821
|
return NotImplemented
|
|
795
822
|
|
|
796
823
|
if (self._special is not None) or (other._special is not None):
|
|
797
824
|
if self._special == "nar" or other._special == "nar":
|
|
798
825
|
return TFloat(float("nan"), self.width)
|
|
826
|
+
if self._special == "inf" == other._special:
|
|
827
|
+
return TFloat(float("nan"), self.width)
|
|
799
828
|
if self._special == "inf" or other._special == "inf":
|
|
800
829
|
return TFloat(float("inf"), self.width)
|
|
801
830
|
if self._special == "zero":
|
|
@@ -863,7 +892,7 @@ class TFloat:
|
|
|
863
892
|
NotImplemented: If widths differ.
|
|
864
893
|
"""
|
|
865
894
|
if not isinstance(other, TFloat):
|
|
866
|
-
raise TypeError
|
|
895
|
+
raise TypeError(f"expected TFloat, got {type(other).__name__}")
|
|
867
896
|
if self.width != other.width:
|
|
868
897
|
return NotImplemented
|
|
869
898
|
|