unary 0.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.
@@ -0,0 +1,14 @@
1
+ # CHANGELOG
2
+
3
+ ## [0.1.0] September 05 2026
4
+
5
+ - First python version ported from the initial 'C' implementation, as written in 2007. The port was done entirely by Claude AI. Doesn't use the 'C' implementation yet (TODO)
6
+
7
+
8
+ ## [0.0.1] 2009
9
+
10
+ - First git hosted version, with minor bug and 'C' compatibility related issues.
11
+
12
+ ## [0.0.0] September 05 2005
13
+
14
+ - Initial 'C' implementation.
unary-0.1.0/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2007 ... 2024, Juha Meskanen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+
@@ -0,0 +1,13 @@
1
+ include *.py
2
+ include *.md
3
+ include *.yml
4
+ include Makefile
5
+ include LICENSE.md
6
+ include README.md
7
+
8
+ # Exclude
9
+ global-exclude __pycache__/*
10
+ global-exclude *.pyc
11
+ global-exclude *.pyo
12
+ global-exclude *~
13
+ global-exclude \#*
unary-0.1.0/Makefile ADDED
@@ -0,0 +1,3 @@
1
+ PROJECT=unary
2
+
3
+ include project.mak
unary-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,210 @@
1
+ Metadata-Version: 2.4
2
+ Name: unary
3
+ Version: 0.1.0
4
+ Summary: Unary arithmetic
5
+ Author-email: J Meskanen <juha@meskanen.com>
6
+ Maintainer-email: "J. Meskanen" <juha@meskanen.com>
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://github.com/juhameskanen/unary
9
+ Project-URL: Bug Reports, https://gitlab.com/juhameskanen/unary
10
+ Project-URL: Source, https://gitlab.com/juhameskanen/unary
11
+ Project-URL: Say Thanks!, http://meskanen.com
12
+ Keywords: unary,arithmetic,calculus,math
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Intended Audience :: Education
16
+ Classifier: Topic :: Scientific/Engineering
17
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
18
+ Classifier: Topic :: Scientific/Engineering :: Physics
19
+ Classifier: Topic :: Education
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.9
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3 :: Only
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: >=3.8
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE.md
31
+ Requires-Dist: requests>=2.31
32
+ Requires-Dist: pytz>=2024.1
33
+ Requires-Dist: colorama>=0.3
34
+ Requires-Dist: typing-extensions>=4.5.0
35
+ Provides-Extra: dev
36
+ Requires-Dist: check-manifest; extra == "dev"
37
+ Requires-Dist: flake8; extra == "dev"
38
+ Requires-Dist: mypy; extra == "dev"
39
+ Requires-Dist: coverage>=7.6; extra == "dev"
40
+ Requires-Dist: pytest-cov; extra == "dev"
41
+ Requires-Dist: types-colorama; extra == "dev"
42
+ Dynamic: license-file
43
+
44
+ # unary (C)
45
+
46
+ Arithmetic on unary numerals using only string operations. A C port of `unary.py`.
47
+
48
+ A natural number *n* is a string of *n* marks. Zero is the empty string.
49
+
50
+ | operation | string operation |
51
+ |----------------|----------------------------------------------------|
52
+ | addition | concatenation |
53
+ | subtraction | suffix removal (truncation) |
54
+ | multiplication | substitution (each mark → a copy of the other numeral) |
55
+ | order (`<=`) | prefix test |
56
+ | divmod | repeated removal |
57
+ | power | repeated multiplication |
58
+ | gcd | Euclid |
59
+ | to binary | repeated pairing-off |
60
+ | from binary | Horner: double the string, append a mark if bit is 1 |
61
+
62
+ ## Layout
63
+
64
+ ```
65
+ unary/ one byte per mark ('|' characters, NUL-terminated)
66
+ unary_packed/ one bit per mark, packed into uint64_t words <- preferred
67
+ unary.h public API
68
+ unary.c implementation
69
+ unary_test.c self-tests
70
+ ```
71
+
72
+ Both directories expose the same function names, so code written against one
73
+ compiles against the other (the `Unary` struct fields differ: `s` vs `w`).
74
+
75
+ ## Build and test
76
+
77
+ ```sh
78
+ cd unary_packed
79
+ gcc -std=c11 -O2 -Wall -Wextra unary.c unary_test.c -o unary_test
80
+ ./unary_test
81
+ ```
82
+
83
+ With sanitizers:
84
+
85
+ ```sh
86
+ gcc -std=c11 -g -Wall -Wextra -Wpedantic -fsanitize=address,undefined \
87
+ unary.c unary_test.c -o unary_test_san && ./unary_test_san
88
+ ```
89
+
90
+ Use it in your own code by compiling `unary.c` alongside your sources and
91
+ including `unary.h`.
92
+
93
+ ## API
94
+
95
+ ```c
96
+ typedef struct { uint64_t *w; size_t len; } Unary; /* packed version */
97
+
98
+ typedef enum { U_OK, U_ERR_NOMEM, U_ERR_INVALID, U_ERR_UNDERFLOW,
99
+ U_ERR_DIV0, U_ERR_OVERFLOW } UStatus;
100
+ const char *u_strerror(UStatus st);
101
+
102
+ /* construction / reading (the external observer's counting) */
103
+ UStatus u_from_str (Unary *out, const char *marks); /* '|' per mark */
104
+ UStatus u_from_size(Unary *out, size_t n);
105
+ size_t u_to_size (const Unary *a);
106
+ UStatus u_to_str (char **out, const Unary *a); /* malloc'd */
107
+ void u_free (Unary *a);
108
+
109
+ /* order */
110
+ bool u_eq(a, b); bool u_le(a, b); bool u_lt(a, b); bool u_is_zero(a);
111
+
112
+ /* arithmetic */
113
+ UStatus u_succ (Unary *out, const Unary *a);
114
+ UStatus u_add (Unary *out, const Unary *a, const Unary *b);
115
+ UStatus u_sub (Unary *out, const Unary *a, const Unary *b); /* U_ERR_UNDERFLOW if b > a */
116
+ UStatus u_mul (Unary *out, const Unary *a, const Unary *b);
117
+ UStatus u_divmod(Unary *q, Unary *r, const Unary *a, const Unary *b); /* U_ERR_DIV0 if b == 0 */
118
+ UStatus u_pow (Unary *out, const Unary *a, const Unary *e); /* 0**0 == 1 */
119
+ UStatus u_gcd (Unary *out, const Unary *a, const Unary *b);
120
+
121
+ /* binary conversion */
122
+ UStatus u_to_binary (char **out, const Unary *a); /* malloc'd; caller free() */
123
+ UStatus u_from_binary(Unary *out, const char *bits);
124
+ ```
125
+
126
+ Example:
127
+
128
+ ```c
129
+ Unary a, b, r;
130
+ u_from_size(&a, 6);
131
+ u_from_size(&b, 7);
132
+ if (u_mul(&r, &a, &b) == U_OK) {
133
+ printf("%zu\n", u_to_size(&r)); /* 42 */
134
+ u_free(&r);
135
+ }
136
+ u_free(&a); u_free(&b);
137
+ ```
138
+
139
+ ### Ownership rules
140
+
141
+ - Every function that fills an `out` numeral allocates it; release it with `u_free()`.
142
+ - `out` must not alias an input.
143
+ - On error, `out` is left empty (`NULL` buffer) and needs no freeing.
144
+ - `u_to_binary` and `u_to_str` return `malloc`'d strings; release with `free()`.
145
+
146
+ ## Packed representation
147
+
148
+ Bit *i* of the numeral lives in `w[i / 64]` at position `i % 64`.
149
+ Canonical form, relied on by `u_eq` and `u_le`:
150
+
151
+ - every bit below `len` is 1;
152
+ - every bit at or above `len` (in the last word and beyond) is 0.
153
+
154
+ Every function preserves this. `u_check_invariant()` verifies it and is used by
155
+ the tests.
156
+
157
+ ## Assumptions and caveats
158
+
159
+ Nothing here is a physical claim. Flagged explicitly:
160
+
161
+ - **Conventions of the reader.** The operations are conventions a reader
162
+ applies to strings of marks; a bare collection of marks has no arithmetic of
163
+ its own.
164
+ - **Pairing convention.** Binary conversion treats two adjacent marks as one
165
+ pair. This presupposes the reader can recognise "two" as a pair of marks.
166
+ - **`len` is bookkeeping.** A C buffer must carry its size. `len` is used for
167
+ buffer sizing, bit positions and overflow guards; the arithmetic itself
168
+ scans and copies marks. `u_to_size()` is the external observer's count (it
169
+ was `to_int()` in Python).
170
+ - **Contents are determined by `len`.** Every stored mark is 1, so the buffer
171
+ holds no information beyond its length. Packing reduces memory 8× relative
172
+ to one byte per mark; it does not change the O(n) space of a unary numeral.
173
+ It is also why `to_binary`'s "pairs become the new number" step is a
174
+ truncation in the packed version.
175
+ - **Overflow guards are an addition.** Size computations return
176
+ `U_ERR_OVERFLOW` where Python would simply run out of memory.
177
+ - **Growth.** Multiplication and exponentiation produce n·m and n^k marks.
178
+ At one bit per mark this is cheaper, but it still exhausts memory quickly.
179
+ A 64-bit-sized value is out of reach for any unary numeral.
180
+
181
+ ## Testing
182
+
183
+ - Reference arithmetic is native `size_t` and an independent binary formatter,
184
+ so the checks do not reuse the code under test.
185
+ - Each result is also checked for canonical form, independently of the
186
+ arithmetic reference.
187
+ - Operand values straddle 64-bit word boundaries (63/64/65, 127/128/129,
188
+ 191/192/193).
189
+ - The harness validates itself: a deliberately wrong add (`a+b+1`) must be
190
+ flagged, and a numeral with a stray bit past `len` must be rejected by the
191
+ invariant check. If either check passes silently the test run aborts.
192
+ - Coverage: all pairs 0..200 for add; 0..300 against the boundary set for
193
+ sub, mul, divmod, gcd, order, binary round trips and error cases; `**` over
194
+ small ranges plus 3^5.
195
+
196
+ ## Measured performance
197
+
198
+ Single runs, `-O2`, one machine, identical benchmark source for both versions.
199
+ Treat as indicative, not definitive.
200
+
201
+ | operation | byte-per-mark | bit-packed |
202
+ |------------------------------|--------------:|-----------:|
203
+ | mul 6000×6000 (36M marks), ×5 | 0.061 s | 0.005 s |
204
+ | add 36M + 36M, ×20 | 0.626 s | 0.027 s |
205
+ | divmod 36M / 7 | 0.031 s | 0.019 s |
206
+ | to_binary 36M | 0.031 s | 0.044 s |
207
+
208
+ A 36M-mark numeral occupies 36 MB in the byte version and 4.5 MB when packed.
209
+ `to_binary` is slower when packed because its pair-finding loop reads two bits
210
+ per step; a word-parallel version would fix that.
unary-0.1.0/README.md ADDED
@@ -0,0 +1,167 @@
1
+ # unary (C)
2
+
3
+ Arithmetic on unary numerals using only string operations. A C port of `unary.py`.
4
+
5
+ A natural number *n* is a string of *n* marks. Zero is the empty string.
6
+
7
+ | operation | string operation |
8
+ |----------------|----------------------------------------------------|
9
+ | addition | concatenation |
10
+ | subtraction | suffix removal (truncation) |
11
+ | multiplication | substitution (each mark → a copy of the other numeral) |
12
+ | order (`<=`) | prefix test |
13
+ | divmod | repeated removal |
14
+ | power | repeated multiplication |
15
+ | gcd | Euclid |
16
+ | to binary | repeated pairing-off |
17
+ | from binary | Horner: double the string, append a mark if bit is 1 |
18
+
19
+ ## Layout
20
+
21
+ ```
22
+ unary/ one byte per mark ('|' characters, NUL-terminated)
23
+ unary_packed/ one bit per mark, packed into uint64_t words <- preferred
24
+ unary.h public API
25
+ unary.c implementation
26
+ unary_test.c self-tests
27
+ ```
28
+
29
+ Both directories expose the same function names, so code written against one
30
+ compiles against the other (the `Unary` struct fields differ: `s` vs `w`).
31
+
32
+ ## Build and test
33
+
34
+ ```sh
35
+ cd unary_packed
36
+ gcc -std=c11 -O2 -Wall -Wextra unary.c unary_test.c -o unary_test
37
+ ./unary_test
38
+ ```
39
+
40
+ With sanitizers:
41
+
42
+ ```sh
43
+ gcc -std=c11 -g -Wall -Wextra -Wpedantic -fsanitize=address,undefined \
44
+ unary.c unary_test.c -o unary_test_san && ./unary_test_san
45
+ ```
46
+
47
+ Use it in your own code by compiling `unary.c` alongside your sources and
48
+ including `unary.h`.
49
+
50
+ ## API
51
+
52
+ ```c
53
+ typedef struct { uint64_t *w; size_t len; } Unary; /* packed version */
54
+
55
+ typedef enum { U_OK, U_ERR_NOMEM, U_ERR_INVALID, U_ERR_UNDERFLOW,
56
+ U_ERR_DIV0, U_ERR_OVERFLOW } UStatus;
57
+ const char *u_strerror(UStatus st);
58
+
59
+ /* construction / reading (the external observer's counting) */
60
+ UStatus u_from_str (Unary *out, const char *marks); /* '|' per mark */
61
+ UStatus u_from_size(Unary *out, size_t n);
62
+ size_t u_to_size (const Unary *a);
63
+ UStatus u_to_str (char **out, const Unary *a); /* malloc'd */
64
+ void u_free (Unary *a);
65
+
66
+ /* order */
67
+ bool u_eq(a, b); bool u_le(a, b); bool u_lt(a, b); bool u_is_zero(a);
68
+
69
+ /* arithmetic */
70
+ UStatus u_succ (Unary *out, const Unary *a);
71
+ UStatus u_add (Unary *out, const Unary *a, const Unary *b);
72
+ UStatus u_sub (Unary *out, const Unary *a, const Unary *b); /* U_ERR_UNDERFLOW if b > a */
73
+ UStatus u_mul (Unary *out, const Unary *a, const Unary *b);
74
+ UStatus u_divmod(Unary *q, Unary *r, const Unary *a, const Unary *b); /* U_ERR_DIV0 if b == 0 */
75
+ UStatus u_pow (Unary *out, const Unary *a, const Unary *e); /* 0**0 == 1 */
76
+ UStatus u_gcd (Unary *out, const Unary *a, const Unary *b);
77
+
78
+ /* binary conversion */
79
+ UStatus u_to_binary (char **out, const Unary *a); /* malloc'd; caller free() */
80
+ UStatus u_from_binary(Unary *out, const char *bits);
81
+ ```
82
+
83
+ Example:
84
+
85
+ ```c
86
+ Unary a, b, r;
87
+ u_from_size(&a, 6);
88
+ u_from_size(&b, 7);
89
+ if (u_mul(&r, &a, &b) == U_OK) {
90
+ printf("%zu\n", u_to_size(&r)); /* 42 */
91
+ u_free(&r);
92
+ }
93
+ u_free(&a); u_free(&b);
94
+ ```
95
+
96
+ ### Ownership rules
97
+
98
+ - Every function that fills an `out` numeral allocates it; release it with `u_free()`.
99
+ - `out` must not alias an input.
100
+ - On error, `out` is left empty (`NULL` buffer) and needs no freeing.
101
+ - `u_to_binary` and `u_to_str` return `malloc`'d strings; release with `free()`.
102
+
103
+ ## Packed representation
104
+
105
+ Bit *i* of the numeral lives in `w[i / 64]` at position `i % 64`.
106
+ Canonical form, relied on by `u_eq` and `u_le`:
107
+
108
+ - every bit below `len` is 1;
109
+ - every bit at or above `len` (in the last word and beyond) is 0.
110
+
111
+ Every function preserves this. `u_check_invariant()` verifies it and is used by
112
+ the tests.
113
+
114
+ ## Assumptions and caveats
115
+
116
+ Nothing here is a physical claim. Flagged explicitly:
117
+
118
+ - **Conventions of the reader.** The operations are conventions a reader
119
+ applies to strings of marks; a bare collection of marks has no arithmetic of
120
+ its own.
121
+ - **Pairing convention.** Binary conversion treats two adjacent marks as one
122
+ pair. This presupposes the reader can recognise "two" as a pair of marks.
123
+ - **`len` is bookkeeping.** A C buffer must carry its size. `len` is used for
124
+ buffer sizing, bit positions and overflow guards; the arithmetic itself
125
+ scans and copies marks. `u_to_size()` is the external observer's count (it
126
+ was `to_int()` in Python).
127
+ - **Contents are determined by `len`.** Every stored mark is 1, so the buffer
128
+ holds no information beyond its length. Packing reduces memory 8× relative
129
+ to one byte per mark; it does not change the O(n) space of a unary numeral.
130
+ It is also why `to_binary`'s "pairs become the new number" step is a
131
+ truncation in the packed version.
132
+ - **Overflow guards are an addition.** Size computations return
133
+ `U_ERR_OVERFLOW` where Python would simply run out of memory.
134
+ - **Growth.** Multiplication and exponentiation produce n·m and n^k marks.
135
+ At one bit per mark this is cheaper, but it still exhausts memory quickly.
136
+ A 64-bit-sized value is out of reach for any unary numeral.
137
+
138
+ ## Testing
139
+
140
+ - Reference arithmetic is native `size_t` and an independent binary formatter,
141
+ so the checks do not reuse the code under test.
142
+ - Each result is also checked for canonical form, independently of the
143
+ arithmetic reference.
144
+ - Operand values straddle 64-bit word boundaries (63/64/65, 127/128/129,
145
+ 191/192/193).
146
+ - The harness validates itself: a deliberately wrong add (`a+b+1`) must be
147
+ flagged, and a numeral with a stray bit past `len` must be rejected by the
148
+ invariant check. If either check passes silently the test run aborts.
149
+ - Coverage: all pairs 0..200 for add; 0..300 against the boundary set for
150
+ sub, mul, divmod, gcd, order, binary round trips and error cases; `**` over
151
+ small ranges plus 3^5.
152
+
153
+ ## Measured performance
154
+
155
+ Single runs, `-O2`, one machine, identical benchmark source for both versions.
156
+ Treat as indicative, not definitive.
157
+
158
+ | operation | byte-per-mark | bit-packed |
159
+ |------------------------------|--------------:|-----------:|
160
+ | mul 6000×6000 (36M marks), ×5 | 0.061 s | 0.005 s |
161
+ | add 36M + 36M, ×20 | 0.626 s | 0.027 s |
162
+ | divmod 36M / 7 | 0.031 s | 0.019 s |
163
+ | to_binary 36M | 0.031 s | 0.044 s |
164
+
165
+ A 36M-mark numeral occupies 36 MB in the byte version and 4.5 MB when packed.
166
+ `to_binary` is slower when packed because its pair-finding loop reads two bits
167
+ per step; a word-parallel version would fix that.
@@ -0,0 +1,70 @@
1
+ [build-system]
2
+ requires = ["setuptools"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [tool.setuptools]
6
+ include-package-data = true
7
+ packages = ["unary"]
8
+
9
+ [tool.setuptools.package-data]
10
+ "unary" = ["py.typed"]
11
+
12
+ [project]
13
+ name = "unary"
14
+ version = "0.1.0"
15
+ description = "Unary arithmetic"
16
+ readme = {file = "README.md", content-type = "text/markdown"}
17
+ requires-python = ">=3.8"
18
+ license = "MIT"
19
+ keywords = ["unary", "arithmetic", "calculus", "math"]
20
+ authors = [
21
+ {name = "J Meskanen", email = "juha@meskanen.com"}
22
+ ]
23
+ maintainers = [
24
+ {name = "J. Meskanen", email = "juha@meskanen.com"}
25
+ ]
26
+ classifiers = [
27
+ "Development Status :: 4 - Beta",
28
+ "Intended Audience :: Science/Research",
29
+ "Intended Audience :: Education",
30
+ "Topic :: Scientific/Engineering",
31
+ "Topic :: Scientific/Engineering :: Mathematics",
32
+ "Topic :: Scientific/Engineering :: Physics",
33
+ "Topic :: Education",
34
+ "Operating System :: OS Independent",
35
+ "Programming Language :: Python :: 3",
36
+ "Programming Language :: Python :: 3.9",
37
+ "Programming Language :: Python :: 3.10",
38
+ "Programming Language :: Python :: 3.11",
39
+ "Programming Language :: Python :: 3.12",
40
+ "Programming Language :: Python :: 3 :: Only",
41
+ "Typing :: Typed",
42
+ ]
43
+
44
+ dependencies = [
45
+ "requests >= 2.31",
46
+ "pytz >= 2024.1",
47
+ "colorama >= 0.3",
48
+ "typing-extensions >= 4.5.0"
49
+ ]
50
+
51
+ [project.optional-dependencies]
52
+ dev = [
53
+ "check-manifest",
54
+ "flake8", "mypy",
55
+ "coverage>=7.6",
56
+ "pytest-cov",
57
+ "types-colorama",
58
+ ]
59
+
60
+ [project.entry-points."unary.plugins"]
61
+
62
+ [project.urls]
63
+ "Homepage" = "https://github.com/juhameskanen/unary"
64
+ "Bug Reports" = "https://gitlab.com/juhameskanen/unary"
65
+ "Source" = "https://gitlab.com/juhameskanen/unary"
66
+ "Say Thanks!" = "http://meskanen.com"
67
+
68
+ [tool.mypy]
69
+ files = "unary, tests"
70
+ ignore_missing_imports = true
unary-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,9 @@
1
+ """
2
+ Unary arithemitc library
3
+
4
+ """
5
+ from .unary import Unary
6
+
7
+ __all__ = [
8
+ "Unary"
9
+ ]
File without changes
@@ -0,0 +1,114 @@
1
+ """
2
+ unary.py -- arithmetic on unary numerals using only string operations.
3
+
4
+ A natural number n is a string of n unary digits '|'. Zero is the empty string.
5
+ No operation below converts to int or counts with len(): addition is
6
+ concatenation, subtraction is suffix removal, multiplication is substitution,
7
+ order is a prefix test, and conversion to binary is repeated pairing-off.
8
+
9
+ The only place a count appears is `to_int`, which is the *external* observer
10
+ reading the result (used by the tests and for display). We keep it out of the
11
+ arithmetic.
12
+
13
+ Assumptions flagged (nothing here is a physical claim):
14
+ * The operations are conventions a reader applies to strings of digits;
15
+ a bare collection of unary digits has no arithmetic of its own.
16
+ * Binary conversion uses the pairing convention '||' -> one pair; this
17
+ presupposes the reader can recognise "two" as a pair of marks.
18
+ """
19
+
20
+ D = "|" # the unary digit
21
+
22
+
23
+ class Unary:
24
+ __slots__ = ("s",)
25
+
26
+ def __init__(self, s: str = ""):
27
+ if any(c != D for c in s):
28
+ raise ValueError(f"unary numeral may contain only {D!r}")
29
+ self.s = s
30
+
31
+ # ---- construction / reading (the external observer's counting) ----
32
+ @classmethod
33
+ def from_int(cls, n: int) -> "Unary":
34
+ if n < 0:
35
+ raise ValueError("naturals only")
36
+ return cls(D * n)
37
+
38
+ def to_int(self) -> int:
39
+ return len(self.s) # external count; not used by any operation below
40
+
41
+ def __repr__(self) -> str:
42
+ return self.s if self.s else "ε"
43
+
44
+ # ---- order: a <= b iff b starts with a (both are runs of D) ----
45
+ def __eq__(self, o): return self.s == o.s
46
+ def __hash__(self): return hash(self.s)
47
+ def __le__(self, o): return o.s.startswith(self.s)
48
+ def __ge__(self, o): return o <= self
49
+ def __lt__(self, o): return self <= o and self != o
50
+ def __gt__(self, o): return o < self
51
+ def __bool__(self): return bool(self.s)
52
+
53
+ # ---- arithmetic ----
54
+ def succ(self) -> "Unary":
55
+ return Unary(self.s + D)
56
+
57
+ def __add__(self, o): return Unary(self.s + o.s) # concatenation
58
+
59
+ def __sub__(self, o): # cancel suffix
60
+ if not o <= self:
61
+ raise ValueError("a - b undefined for b > a in the naturals")
62
+ return Unary(self.s.removesuffix(o.s))
63
+
64
+ def __mul__(self, o): return Unary(self.s.replace(D, o.s)) # each mark -> copy of o
65
+
66
+ def __divmod__(self, o): # repeated removal
67
+ if not o:
68
+ raise ZeroDivisionError("division by zero")
69
+ q, r = Unary(), self
70
+ while o <= r:
71
+ r = r - o
72
+ q = q.succ()
73
+ return q, r
74
+
75
+ def __floordiv__(self, o): return divmod(self, o)[0]
76
+ def __mod__(self, o): return divmod(self, o)[1]
77
+
78
+ def __pow__(self, o): # repeated multiplication
79
+ result = Unary(D)
80
+ for _ in o.s:
81
+ result = result * self
82
+ return result
83
+
84
+ def gcd(self, o) -> "Unary": # Euclid
85
+ a, b = self, o
86
+ while b:
87
+ a, b = b, a % b
88
+ return a
89
+
90
+ # ---- conversion: unary <-> binary ----
91
+ def to_binary(self) -> str:
92
+ """Pair off marks; the leftover mark (or its absence) is the next bit
93
+ (least significant first); the pairs become the new number; repeat."""
94
+ n, bits = self.s, []
95
+ if not n:
96
+ return "0"
97
+ while n:
98
+ t = n.replace(D + D, "#") # '#' = one pair, D = leftover
99
+ bits.append("1" if D in t else "0")
100
+ n = t.replace(D, "").replace("#", D)
101
+ return "".join(reversed(bits))
102
+
103
+ @classmethod
104
+ def from_binary(cls, bits: str) -> "Unary":
105
+ """Horner: for each bit, double the string; append one mark if bit is 1."""
106
+ u = Unary()
107
+ for c in bits:
108
+ if c not in "01":
109
+ raise ValueError("binary string expected")
110
+ u = u + u
111
+ if c == "1":
112
+ u = u.succ()
113
+ return u
114
+
@@ -0,0 +1,210 @@
1
+ Metadata-Version: 2.4
2
+ Name: unary
3
+ Version: 0.1.0
4
+ Summary: Unary arithmetic
5
+ Author-email: J Meskanen <juha@meskanen.com>
6
+ Maintainer-email: "J. Meskanen" <juha@meskanen.com>
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://github.com/juhameskanen/unary
9
+ Project-URL: Bug Reports, https://gitlab.com/juhameskanen/unary
10
+ Project-URL: Source, https://gitlab.com/juhameskanen/unary
11
+ Project-URL: Say Thanks!, http://meskanen.com
12
+ Keywords: unary,arithmetic,calculus,math
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Intended Audience :: Education
16
+ Classifier: Topic :: Scientific/Engineering
17
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
18
+ Classifier: Topic :: Scientific/Engineering :: Physics
19
+ Classifier: Topic :: Education
20
+ Classifier: Operating System :: OS Independent
21
+ Classifier: Programming Language :: Python :: 3
22
+ Classifier: Programming Language :: Python :: 3.9
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3 :: Only
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: >=3.8
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE.md
31
+ Requires-Dist: requests>=2.31
32
+ Requires-Dist: pytz>=2024.1
33
+ Requires-Dist: colorama>=0.3
34
+ Requires-Dist: typing-extensions>=4.5.0
35
+ Provides-Extra: dev
36
+ Requires-Dist: check-manifest; extra == "dev"
37
+ Requires-Dist: flake8; extra == "dev"
38
+ Requires-Dist: mypy; extra == "dev"
39
+ Requires-Dist: coverage>=7.6; extra == "dev"
40
+ Requires-Dist: pytest-cov; extra == "dev"
41
+ Requires-Dist: types-colorama; extra == "dev"
42
+ Dynamic: license-file
43
+
44
+ # unary (C)
45
+
46
+ Arithmetic on unary numerals using only string operations. A C port of `unary.py`.
47
+
48
+ A natural number *n* is a string of *n* marks. Zero is the empty string.
49
+
50
+ | operation | string operation |
51
+ |----------------|----------------------------------------------------|
52
+ | addition | concatenation |
53
+ | subtraction | suffix removal (truncation) |
54
+ | multiplication | substitution (each mark → a copy of the other numeral) |
55
+ | order (`<=`) | prefix test |
56
+ | divmod | repeated removal |
57
+ | power | repeated multiplication |
58
+ | gcd | Euclid |
59
+ | to binary | repeated pairing-off |
60
+ | from binary | Horner: double the string, append a mark if bit is 1 |
61
+
62
+ ## Layout
63
+
64
+ ```
65
+ unary/ one byte per mark ('|' characters, NUL-terminated)
66
+ unary_packed/ one bit per mark, packed into uint64_t words <- preferred
67
+ unary.h public API
68
+ unary.c implementation
69
+ unary_test.c self-tests
70
+ ```
71
+
72
+ Both directories expose the same function names, so code written against one
73
+ compiles against the other (the `Unary` struct fields differ: `s` vs `w`).
74
+
75
+ ## Build and test
76
+
77
+ ```sh
78
+ cd unary_packed
79
+ gcc -std=c11 -O2 -Wall -Wextra unary.c unary_test.c -o unary_test
80
+ ./unary_test
81
+ ```
82
+
83
+ With sanitizers:
84
+
85
+ ```sh
86
+ gcc -std=c11 -g -Wall -Wextra -Wpedantic -fsanitize=address,undefined \
87
+ unary.c unary_test.c -o unary_test_san && ./unary_test_san
88
+ ```
89
+
90
+ Use it in your own code by compiling `unary.c` alongside your sources and
91
+ including `unary.h`.
92
+
93
+ ## API
94
+
95
+ ```c
96
+ typedef struct { uint64_t *w; size_t len; } Unary; /* packed version */
97
+
98
+ typedef enum { U_OK, U_ERR_NOMEM, U_ERR_INVALID, U_ERR_UNDERFLOW,
99
+ U_ERR_DIV0, U_ERR_OVERFLOW } UStatus;
100
+ const char *u_strerror(UStatus st);
101
+
102
+ /* construction / reading (the external observer's counting) */
103
+ UStatus u_from_str (Unary *out, const char *marks); /* '|' per mark */
104
+ UStatus u_from_size(Unary *out, size_t n);
105
+ size_t u_to_size (const Unary *a);
106
+ UStatus u_to_str (char **out, const Unary *a); /* malloc'd */
107
+ void u_free (Unary *a);
108
+
109
+ /* order */
110
+ bool u_eq(a, b); bool u_le(a, b); bool u_lt(a, b); bool u_is_zero(a);
111
+
112
+ /* arithmetic */
113
+ UStatus u_succ (Unary *out, const Unary *a);
114
+ UStatus u_add (Unary *out, const Unary *a, const Unary *b);
115
+ UStatus u_sub (Unary *out, const Unary *a, const Unary *b); /* U_ERR_UNDERFLOW if b > a */
116
+ UStatus u_mul (Unary *out, const Unary *a, const Unary *b);
117
+ UStatus u_divmod(Unary *q, Unary *r, const Unary *a, const Unary *b); /* U_ERR_DIV0 if b == 0 */
118
+ UStatus u_pow (Unary *out, const Unary *a, const Unary *e); /* 0**0 == 1 */
119
+ UStatus u_gcd (Unary *out, const Unary *a, const Unary *b);
120
+
121
+ /* binary conversion */
122
+ UStatus u_to_binary (char **out, const Unary *a); /* malloc'd; caller free() */
123
+ UStatus u_from_binary(Unary *out, const char *bits);
124
+ ```
125
+
126
+ Example:
127
+
128
+ ```c
129
+ Unary a, b, r;
130
+ u_from_size(&a, 6);
131
+ u_from_size(&b, 7);
132
+ if (u_mul(&r, &a, &b) == U_OK) {
133
+ printf("%zu\n", u_to_size(&r)); /* 42 */
134
+ u_free(&r);
135
+ }
136
+ u_free(&a); u_free(&b);
137
+ ```
138
+
139
+ ### Ownership rules
140
+
141
+ - Every function that fills an `out` numeral allocates it; release it with `u_free()`.
142
+ - `out` must not alias an input.
143
+ - On error, `out` is left empty (`NULL` buffer) and needs no freeing.
144
+ - `u_to_binary` and `u_to_str` return `malloc`'d strings; release with `free()`.
145
+
146
+ ## Packed representation
147
+
148
+ Bit *i* of the numeral lives in `w[i / 64]` at position `i % 64`.
149
+ Canonical form, relied on by `u_eq` and `u_le`:
150
+
151
+ - every bit below `len` is 1;
152
+ - every bit at or above `len` (in the last word and beyond) is 0.
153
+
154
+ Every function preserves this. `u_check_invariant()` verifies it and is used by
155
+ the tests.
156
+
157
+ ## Assumptions and caveats
158
+
159
+ Nothing here is a physical claim. Flagged explicitly:
160
+
161
+ - **Conventions of the reader.** The operations are conventions a reader
162
+ applies to strings of marks; a bare collection of marks has no arithmetic of
163
+ its own.
164
+ - **Pairing convention.** Binary conversion treats two adjacent marks as one
165
+ pair. This presupposes the reader can recognise "two" as a pair of marks.
166
+ - **`len` is bookkeeping.** A C buffer must carry its size. `len` is used for
167
+ buffer sizing, bit positions and overflow guards; the arithmetic itself
168
+ scans and copies marks. `u_to_size()` is the external observer's count (it
169
+ was `to_int()` in Python).
170
+ - **Contents are determined by `len`.** Every stored mark is 1, so the buffer
171
+ holds no information beyond its length. Packing reduces memory 8× relative
172
+ to one byte per mark; it does not change the O(n) space of a unary numeral.
173
+ It is also why `to_binary`'s "pairs become the new number" step is a
174
+ truncation in the packed version.
175
+ - **Overflow guards are an addition.** Size computations return
176
+ `U_ERR_OVERFLOW` where Python would simply run out of memory.
177
+ - **Growth.** Multiplication and exponentiation produce n·m and n^k marks.
178
+ At one bit per mark this is cheaper, but it still exhausts memory quickly.
179
+ A 64-bit-sized value is out of reach for any unary numeral.
180
+
181
+ ## Testing
182
+
183
+ - Reference arithmetic is native `size_t` and an independent binary formatter,
184
+ so the checks do not reuse the code under test.
185
+ - Each result is also checked for canonical form, independently of the
186
+ arithmetic reference.
187
+ - Operand values straddle 64-bit word boundaries (63/64/65, 127/128/129,
188
+ 191/192/193).
189
+ - The harness validates itself: a deliberately wrong add (`a+b+1`) must be
190
+ flagged, and a numeral with a stray bit past `len` must be rejected by the
191
+ invariant check. If either check passes silently the test run aborts.
192
+ - Coverage: all pairs 0..200 for add; 0..300 against the boundary set for
193
+ sub, mul, divmod, gcd, order, binary round trips and error cases; `**` over
194
+ small ranges plus 3^5.
195
+
196
+ ## Measured performance
197
+
198
+ Single runs, `-O2`, one machine, identical benchmark source for both versions.
199
+ Treat as indicative, not definitive.
200
+
201
+ | operation | byte-per-mark | bit-packed |
202
+ |------------------------------|--------------:|-----------:|
203
+ | mul 6000×6000 (36M marks), ×5 | 0.061 s | 0.005 s |
204
+ | add 36M + 36M, ×20 | 0.626 s | 0.027 s |
205
+ | divmod 36M / 7 | 0.031 s | 0.019 s |
206
+ | to_binary 36M | 0.031 s | 0.044 s |
207
+
208
+ A 36M-mark numeral occupies 36 MB in the byte version and 4.5 MB when packed.
209
+ `to_binary` is slower when packed because its pair-finding loop reads two bits
210
+ per step; a word-parallel version would fix that.
@@ -0,0 +1,14 @@
1
+ CHANGELOG.md
2
+ LICENSE.md
3
+ MANIFEST.in
4
+ Makefile
5
+ README.md
6
+ pyproject.toml
7
+ unary/__init__.py
8
+ unary/py.typed
9
+ unary/unary.py
10
+ unary.egg-info/PKG-INFO
11
+ unary.egg-info/SOURCES.txt
12
+ unary.egg-info/dependency_links.txt
13
+ unary.egg-info/requires.txt
14
+ unary.egg-info/top_level.txt
@@ -0,0 +1,12 @@
1
+ requests>=2.31
2
+ pytz>=2024.1
3
+ colorama>=0.3
4
+ typing-extensions>=4.5.0
5
+
6
+ [dev]
7
+ check-manifest
8
+ flake8
9
+ mypy
10
+ coverage>=7.6
11
+ pytest-cov
12
+ types-colorama
@@ -0,0 +1 @@
1
+ unary