csdigit 0.1__py3-none-any.whl

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.
csdigit/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ import sys
2
+
3
+ if sys.version_info[:2] >= (3, 8):
4
+ # TODO: Import directly (no need for conditional) when `python_requires = >= 3.9`
5
+ from importlib.metadata import PackageNotFoundError, version # pragma: no cover
6
+ else:
7
+ from importlib_metadata import PackageNotFoundError, version # pragma: no cover
8
+
9
+ try:
10
+ # Change here if project is renamed and does not equal the package name
11
+ dist_name = __name__
12
+ __version__ = version(dist_name)
13
+ except PackageNotFoundError: # pragma: no cover
14
+ __version__ = "unknown"
15
+ finally:
16
+ del version, PackageNotFoundError
csdigit/cli.py ADDED
@@ -0,0 +1,179 @@
1
+ """
2
+ This is a to_csd file that can serve as a starting point for a Python
3
+ console script. To run this script uncomment the following lines in the
4
+ ``[options.entry_points]`` section in ``setup.cfg``::
5
+
6
+ console_scripts =
7
+ to_csd = csdigit.to_csd:run
8
+
9
+ Then run ``pip install .`` (or ``pip install -e .`` for editable mode)
10
+ which will install the command ``to_csd`` inside your current environment.
11
+
12
+ Besides console scripts, the header (i.e. until ``_logger``...) of this file can
13
+ also be used as template for Python modules.
14
+
15
+ References:
16
+ - https://setuptools.readthedocs.io/en/latest/userguide/entry_point.html
17
+ - https://pip.pypa.io/en/stable/reference/pip_install
18
+ """
19
+
20
+ import argparse
21
+ import logging
22
+ import sys
23
+
24
+ from csdigit import __version__
25
+ from csdigit.csd import to_csd, to_csdnnz, to_decimal
26
+
27
+ __author__ = "Wai-Shing Luk"
28
+ __copyright__ = "Wai-Shing Luk"
29
+ __license__ = "MIT"
30
+
31
+ _logger = logging.getLogger(__name__)
32
+
33
+
34
+ # ---- CLI ----
35
+ # The functions defined in this section are wrappers around the main Python
36
+ # API allowing them to be called directly from the terminal as a CLI
37
+ # executable/script.
38
+
39
+
40
+ def parse_args(args):
41
+ """Parse command line parameters
42
+
43
+ Args:
44
+ args (List[str]): command line parameters as list of strings
45
+ (for example ``["--help"]``).
46
+
47
+ Returns:
48
+ :obj:`argparse.Namespace`: command line parameters namespace
49
+ """
50
+ parser = argparse.ArgumentParser(description="Converts a decimal to a CSD format")
51
+ parser.add_argument(
52
+ "--version",
53
+ action="version",
54
+ version="csdigit {ver}".format(ver=__version__),
55
+ )
56
+ parser.add_argument(
57
+ "-c",
58
+ "--to_csd",
59
+ dest="decimal",
60
+ help="a decimal number",
61
+ type=float,
62
+ metavar="FLOAT",
63
+ default=float("Inf"),
64
+ )
65
+ parser.add_argument(
66
+ "-f",
67
+ "--to_csdnnz",
68
+ dest="decimal2",
69
+ help="a decimal number",
70
+ type=float,
71
+ metavar="FLOAT",
72
+ default=float("Inf"),
73
+ )
74
+ parser.add_argument(
75
+ "-d",
76
+ "--to_decimal",
77
+ dest="csdstr",
78
+ help="a CSD string",
79
+ type=str,
80
+ metavar="STR",
81
+ default="",
82
+ )
83
+ parser.add_argument(
84
+ "-p",
85
+ "--places",
86
+ dest="places",
87
+ help="How many places",
88
+ type=int,
89
+ metavar="INT",
90
+ default=4,
91
+ )
92
+ parser.add_argument(
93
+ "-z",
94
+ "--nnz",
95
+ dest="nnz",
96
+ help="How many non-zeros",
97
+ type=int,
98
+ metavar="INT",
99
+ default=4,
100
+ )
101
+ parser.add_argument(
102
+ "-v",
103
+ "--verbose",
104
+ dest="loglevel",
105
+ help="set loglevel to INFO",
106
+ action="store_const",
107
+ const=logging.INFO,
108
+ )
109
+ parser.add_argument(
110
+ "-vv",
111
+ "--very-verbose",
112
+ dest="loglevel",
113
+ help="set loglevel to DEBUG",
114
+ action="store_const",
115
+ const=logging.DEBUG,
116
+ )
117
+ return parser.parse_args(args)
118
+
119
+
120
+ def setup_logging(loglevel) -> None:
121
+ """Setup basic logging
122
+
123
+ Args:
124
+ loglevel (int): minimum loglevel for emitting messages
125
+ """
126
+ logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
127
+ logging.basicConfig(
128
+ level=loglevel,
129
+ stream=sys.stdout,
130
+ format=logformat,
131
+ datefmt="%Y-%m-%d %H:%M:%S",
132
+ )
133
+
134
+
135
+ def main(args) -> None:
136
+ """Wrapper allowing :func:`fib` to be called with string arguments in a CLI fashion
137
+
138
+ Instead of returning the value from :func:`fib`, it prints the result to the
139
+ ``stdout`` in a nicely formatted message.
140
+
141
+ Args:
142
+ args (List[str]): command line parameters as list of strings
143
+ (for example ``["--verbose", "42"]``).
144
+ """
145
+ args = parse_args(args)
146
+ setup_logging(args.loglevel)
147
+ _logger.debug("Starting crazy calculations...")
148
+ if args.decimal != float("Inf"):
149
+ ans = to_csd(args.decimal, args.places)
150
+ print(f"{ans}")
151
+ if args.decimal2 != float("Inf"):
152
+ ans = to_csdnnz(args.decimal2, args.nnz)
153
+ print(f"{ans}")
154
+ if args.csdstr != "":
155
+ ans = to_decimal(args.csdstr)
156
+ print(f"{ans}")
157
+ _logger.info("Script ends here")
158
+
159
+
160
+ def run() -> None:
161
+ """Calls :func:`main` passing the CLI arguments extracted from :obj:`sys.argv`
162
+
163
+ This function can be used as entry point to create console scripts with setuptools.
164
+ """
165
+ main(sys.argv[1:])
166
+
167
+
168
+ if __name__ == "__main__":
169
+ # ^ This is a guard statement that will prevent the following code from
170
+ # being executed in the case someone imports this file instead of
171
+ # executing it as a script.
172
+ # https://docs.python.org/3/library/__main__.html
173
+
174
+ # After installing your project with pip, users can also run your Python
175
+ # modules as scripts via the ``-m`` flag, as defined in PEP 338::
176
+ #
177
+ # python -m csdigit.to_csd 42
178
+ #
179
+ run()
csdigit/csd.py ADDED
@@ -0,0 +1,309 @@
1
+ """
2
+ Canonical Signed Digit (CSD) Conversion
3
+
4
+ This code is all about converting numbers between decimal format and a special representation called Canonical Signed Digit (CSD). CSD is a way of writing numbers using only three symbols: 0, +, and -. It's particularly useful in certain areas of computer science and digital signal processing.
5
+
6
+ The main purpose of this code is to provide functions that can convert decimal numbers to CSD format and vice versa. It takes in regular decimal numbers (like 28.5 or -0.5) and converts them to CSD strings (like "+00-00.+" or "0.-"), and it can also do the reverse, taking CSD strings and converting them back to decimal numbers.
7
+
8
+ The code contains several functions, each with a specific role:
9
+
10
+ 1. to_csd: This function takes a decimal number and the number of decimal places desired, and outputs a CSD string. For example, it can convert 28.5 to "+00-00.+0" (with 2 decimal places).
11
+
12
+ 2. to_csd_i: Similar to to_csd, but it works specifically with integers. It converts whole numbers to CSD format without a decimal point.
13
+
14
+ 3. to_decimal_using_pow and to_decimal: These functions do the opposite of to_csd. They take a CSD string and convert it back to a decimal number.
15
+
16
+ 4. to_csdnnz: This function is a variation of to_csd that allows you to specify the maximum number of non-zero digits in the result.
17
+
18
+ The code achieves its purpose through a series of mathematical operations and logical checks. For the decimal to CSD conversion, it uses powers of 2 to determine which symbols (+, -, or 0) to use at each position in the CSD string. It repeatedly divides the input number by 2 and checks if it's greater than, less than, or close to certain thresholds to decide which symbol to use.
19
+
20
+ For the CSD to decimal conversion, it goes through each symbol in the CSD string, multiplying the running total by 2 and adding 1, subtracting 1, or doing nothing based on whether the symbol is +, -, or 0.
21
+
22
+ An important aspect of the code is how it handles the decimal point in CSD representations. It uses a separate logic for the part before the decimal point (the integral part) and the part after (the fractional part).
23
+
24
+ The code also includes error checking to ensure that only valid CSD symbols are used, and it provides detailed documentation and examples for each function to help users understand how to use them.
25
+
26
+ Overall, this code provides a comprehensive set of tools for working with CSD representations, allowing users to easily convert between decimal and CSD formats in various ways.
27
+ """
28
+
29
+ from math import ceil, fabs, log
30
+ from typing import Tuple
31
+
32
+ ERROR1 = "Work with 0, +, -, and . only"
33
+ ERROR2 = "Work with 0, +, and - only"
34
+
35
+
36
+ def to_csd(decimal_value: float, places: int) -> str:
37
+ """
38
+ The `to_csd` function converts a given decimal number to its Canonical Signed Digit (CSD)
39
+ representation with a specified number of decimal places.
40
+
41
+ Original author: Harnesser
42
+ <https://sourceforge.net/projects/pycsd/>
43
+ License: GPL2
44
+
45
+ :param decimal_value: The `decimal_value` parameter is a double precision floating-point number that represents the
46
+ value to be converted to CSD (Canonical Signed Digit) representation
47
+ :type decimal_value: float
48
+ :param places: The `places` parameter in the `to_csd` function represents the number of decimal
49
+ places to include in the CSD (Canonical Signed Digit) representation of the given `decimal_value`
50
+ :type places: int
51
+ :return: The function `to_csd` returns a string representation of the given `decimal_value` in Canonical
52
+ Signed Digit (CSD) format.
53
+
54
+ Examples:
55
+ >>> to_csd(28.5, 2)
56
+ '+00-00.+0'
57
+ >>> to_csd(-0.5, 2)
58
+ '0.-0'
59
+ >>> to_csd(0.0, 2)
60
+ '0.00'
61
+ >>> to_csd(0.0, 0)
62
+ '0.'
63
+ """
64
+ absnum = fabs(decimal_value)
65
+ if absnum < 1.0:
66
+ rem = 0
67
+ csd = "0"
68
+ else:
69
+ rem = int(ceil(log(absnum * 1.5, 2)))
70
+ csd = ""
71
+ p2n = pow(2.0, rem)
72
+
73
+ def loop_fn(value):
74
+ nonlocal rem, decimal_value, p2n, csd
75
+ while rem > value:
76
+ rem -= 1
77
+ p2n /= 2.0
78
+ det = 1.5 * decimal_value
79
+ if det > p2n:
80
+ csd += "+"
81
+ decimal_value -= p2n
82
+ elif det < -p2n:
83
+ csd += "-"
84
+ decimal_value += p2n
85
+ else:
86
+ csd += "0"
87
+
88
+ loop_fn(0)
89
+ csd += "."
90
+ loop_fn(-places)
91
+ return csd
92
+
93
+
94
+ def to_csd_i(decimal_value: int) -> str:
95
+ """
96
+ The `to_csd_i` function converts a given integer into a Canonical Signed Digit (CSD) representation.
97
+
98
+ Original author: Harnesser
99
+ <https://sourceforge.net/projects/pycsd/>
100
+ License: GPL2
101
+
102
+ :param decimal_value: The `decimal_value` parameter is an integer that represents the decimal value to be converted to
103
+ CSD format
104
+ :type decimal_value: int
105
+ :return: The function `to_csd_i` returns a string containing the CSD (Canonical Signed Digit) value.
106
+
107
+ Examples:
108
+ >>> to_csd_i(28)
109
+ '+00-00'
110
+ >>> to_csd_i(-0)
111
+ '0'
112
+ >>> to_csd_i(0)
113
+ '0'
114
+ """
115
+ # figure out binary range, special case for 0
116
+ if decimal_value == 0:
117
+ return "0"
118
+
119
+ rem = ceil(log(abs(decimal_value) * 1.5, 2))
120
+ p2n = pow(2, rem)
121
+ csd = ""
122
+ while p2n > 1:
123
+ # convert the number
124
+ p2n_half = p2n >> 1
125
+ det = 3 * decimal_value
126
+ if det > p2n:
127
+ csd += "+"
128
+ decimal_value -= p2n_half
129
+ elif det < -p2n:
130
+ csd += "-"
131
+ decimal_value += p2n_half
132
+ else:
133
+ csd += "0"
134
+ p2n = p2n_half
135
+ return csd
136
+
137
+
138
+ def to_decimal_using_pow(csd: str) -> float:
139
+ """
140
+ The `to_decimal_using_pow` function converts a Canonical Signed Digit (CSD) string to a decimal
141
+ number using the pow function.
142
+
143
+ Original author: Harnesser
144
+ <https://sourceforge.net/projects/pycsd/>
145
+ License: GPL2
146
+
147
+ :param csd: The `csd` parameter is a string containing the CSD (Canonical Signed Digit) value
148
+ :type csd: str
149
+
150
+ Examples:
151
+ >>> to_decimal_using_pow("+00-00.+")
152
+ 28.5
153
+ >>> to_decimal_using_pow("0.-")
154
+ -0.5
155
+ >>> to_decimal_using_pow("0")
156
+ 0.0
157
+ >>> to_decimal_using_pow("0.0")
158
+ 0.0
159
+ >>> to_decimal_using_pow("0.+")
160
+ 0.5
161
+ """
162
+
163
+ decimal_value: float = 0.0
164
+ loc: int = 0
165
+ for pos, digit in enumerate(csd):
166
+ if digit == "0":
167
+ decimal_value *= 2.0
168
+ elif digit == "+":
169
+ decimal_value = decimal_value * 2.0 + 1.0
170
+ elif digit == "-":
171
+ decimal_value = decimal_value * 2.0 - 1.0
172
+ elif digit == ".":
173
+ loc = pos + 1
174
+ else:
175
+ raise ValueError(ERROR1)
176
+ if loc != 0:
177
+ decimal_value /= pow(2.0, len(csd) - loc)
178
+
179
+ return decimal_value
180
+
181
+
182
+ def to_decimal_integral(csd: str) -> Tuple[int, int]:
183
+ """Handle integral part of CSD string."""
184
+ decimal_value: int = 0
185
+ for pos, digit in enumerate(csd):
186
+ if digit == "0":
187
+ decimal_value <<= 1
188
+ elif digit == "+":
189
+ decimal_value = (decimal_value << 1) + 1
190
+ elif digit == "-":
191
+ decimal_value = (decimal_value << 1) - 1
192
+ elif digit == ".":
193
+ return decimal_value, pos + 1
194
+ else:
195
+ raise ValueError(ERROR1)
196
+ return decimal_value, 0
197
+
198
+
199
+ def to_decimal_fractional(csd: str) -> float:
200
+ """Handle fractional part of CSD string."""
201
+ decimal_value = 0.0
202
+ scale = 0.5
203
+ for digit in csd:
204
+ if digit == "0":
205
+ pass
206
+ elif digit == "+":
207
+ decimal_value += scale
208
+ elif digit == "-":
209
+ decimal_value -= scale
210
+ else:
211
+ raise ValueError(ERROR1)
212
+ scale /= 2.0
213
+ return decimal_value
214
+
215
+
216
+ def to_decimal(csd: str) -> float:
217
+ """Convert CSD string to decimal number.
218
+
219
+ Original author: Harnesser
220
+ <https://sourceforge.net/projects/pycsd/>
221
+ License: GPL2
222
+
223
+ :param csd: The `csd` parameter is a string containing the CSD (Canonical Signed Digit) value that
224
+ we want to convert to a decimal number
225
+
226
+ :type csd: str
227
+
228
+ Examples:
229
+ >>> to_decimal("+00-00.+")
230
+ 28.5
231
+ >>> to_decimal("0.-")
232
+ -0.5
233
+ >>> to_decimal("0")
234
+ 0
235
+ >>> to_decimal("0.0")
236
+ 0.0
237
+ >>> to_decimal("0.+")
238
+ 0.5
239
+ """
240
+ integral, loc = to_decimal_integral(csd)
241
+ if loc == 0:
242
+ return integral
243
+
244
+ fractional = to_decimal_fractional(csd[loc:])
245
+ return integral + fractional
246
+
247
+
248
+ def to_csdnnz(decimal_value: float, nnz: int) -> str:
249
+ """
250
+ The `to_csdnnz` function converts a given decimal number into a Canonical Signed Digit (CSD)
251
+ representation with a specified number of non-zero digits.
252
+
253
+ Original author: Harnesser
254
+ <https://sourceforge.net/projects/pycsd/>
255
+ License: GPL2
256
+
257
+ :param decimal_value: The `decimal_value` parameter is a double precision floating-point number that represents the
258
+ input value for conversion to CSD (Canonic Signed Digit) fixed-point representation
259
+ :type decimal_value: float
260
+ :param nnz: The parameter `nnz` stands for "number of non-zero bits". It represents the maximum
261
+ number of non-zero bits allowed in the output CSD (Canonical Signed Digit) representation of the
262
+ given `decimal_value`
263
+ :type nnz: int
264
+ :return: The function `to_csdnnz` returns a string representation of the given `decimal_value` in Canonical
265
+ Signed Digit (CSD) format.
266
+
267
+ Examples:
268
+ >>> to_csdnnz(28.5, 4)
269
+ '+00-00.+'
270
+ >>> to_csdnnz(-0.5, 4)
271
+ '0.-'
272
+ >>> to_csdnnz(0.0, 4)
273
+ '0'
274
+ >>> to_csdnnz(0.5, 4)
275
+ '0.+'
276
+ """
277
+ absnum = fabs(decimal_value)
278
+ if absnum < 1.0:
279
+ rem = 0
280
+ csd = "0"
281
+ else:
282
+ rem = ceil(log(absnum * 1.5, 2))
283
+ csd = ""
284
+ p2n = pow(2, rem)
285
+ while rem > 0 or (nnz > 0 and fabs(decimal_value) > 1e-100):
286
+ if rem == 0:
287
+ csd += "."
288
+ p2n /= 2
289
+ rem -= 1
290
+ det = 1.5 * decimal_value
291
+ if det > p2n:
292
+ csd += "+"
293
+ decimal_value -= p2n
294
+ nnz -= 1
295
+ elif det < -p2n:
296
+ csd += "-"
297
+ decimal_value += p2n
298
+ nnz -= 1
299
+ else:
300
+ csd += "0"
301
+ if nnz == 0:
302
+ decimal_value = 0.0
303
+ return csd
304
+
305
+
306
+ if __name__ == "__main__":
307
+ import doctest
308
+
309
+ doctest.testmod()
csdigit/lcsre.py ADDED
@@ -0,0 +1,87 @@
1
+ """
2
+ Longest Repeated Substring Finder
3
+
4
+ This code defines a function called longest_repeated_substring that finds the longest repeated non-overlapping substring within a given string. The purpose of this code is to identify and return the longest sequence of characters that appears more than once in the input string, without the repetitions overlapping each other.
5
+
6
+ The function takes a single input: a string called cs, which represents the text in which we want to find the repeated substring. The output of the function is another string, which is the longest repeated non-overlapping substring found in the input.
7
+
8
+ To achieve its purpose, the code uses a dynamic programming approach. It creates a 2D table (called LCSRe) to keep track of the lengths of repeated substrings at different positions in the input string. The algorithm then iterates through this table, comparing characters and updating the lengths of repeated substrings it finds.
9
+
10
+ The main logic flow of the algorithm is as follows:
11
+
12
+ 1. Initialize the 2D table with zeros.
13
+ 2. Iterate through the table, comparing characters of the input string.
14
+ 3. When matching characters are found, update the length of the repeated substring in the table.
15
+ 4. Keep track of the maximum length of repeated substring found and its ending position.
16
+ 5. After filling the table, extract the longest repeated substring from the input string using the recorded length and position.
17
+
18
+ An important aspect of this algorithm is that it avoids overlapping substrings. This is achieved by checking if the distance between the current positions is greater than the length of the previously found repeated substring.
19
+
20
+ The code also includes a simple example usage, where it applies the function to the string "+-00+-00+-00+-0". This demonstrates how the function can be used and what kind of output it produces.
21
+
22
+ In summary, this code provides a way to find the longest sequence of characters that repeats in a given text, which can be useful in various text processing and analysis tasks. It uses a clever approach to solve what could otherwise be a computationally expensive problem, making it efficient for longer input strings.
23
+ """
24
+
25
+ # Python 3 program to find the longest repeated
26
+ # non-overlapping substring
27
+
28
+
29
+ def longest_repeated_substring(cs: str) -> str:
30
+ """Longest repeated non-overlapping substring
31
+
32
+ The `longest_repeated_substring` function takes a string as input and returns the longest repeated
33
+ substring in the string.
34
+
35
+ :param cs: The parameter `cs` is a string containing the CSD value
36
+
37
+ :type cs: str
38
+
39
+ :return: The function `longest_repeated_substring` returns a string, which is the longest repeated
40
+ substring in the given input string `cs`.
41
+
42
+ Examples:
43
+ >>> longest_repeated_substring("+-00+-00+-00+-0")
44
+ '+-00+-0'
45
+ """
46
+ ndim = len(cs) + 1
47
+ LCSRe = [[0 for _ in range(ndim)] for _ in range(ndim)]
48
+
49
+ res = "" # To store result
50
+ res_length = 0 # To store length of result
51
+
52
+ # building table in bottom-up manner
53
+ index = 0
54
+ for i in range(1, ndim):
55
+ for j in range(i + 1, ndim):
56
+ # (j-i) > LCSRe[i-1][j-1] to remove
57
+ # overlapping
58
+ if cs[i - 1] == cs[j - 1] and LCSRe[i - 1][j - 1] < (j - i):
59
+ LCSRe[i][j] = LCSRe[i - 1][j - 1] + 1
60
+
61
+ # updating maximum length of the
62
+ # substring and updating the finishing
63
+ # index of the suffix
64
+ if LCSRe[i][j] > res_length:
65
+ res_length = LCSRe[i][j]
66
+ index = max(i, index)
67
+
68
+ else:
69
+ LCSRe[i][j] = 0
70
+
71
+ # If we have non-empty result, then insert
72
+ # all characters from first character to
73
+ # last character of string
74
+ if res_length > 0:
75
+ # for i in range(index - res_length + 1, index + 1):
76
+ # res = res + cs[i - 1]
77
+ res = cs[index - res_length : index]
78
+
79
+ return res
80
+
81
+
82
+ # Driver Code
83
+ if __name__ == "__main__":
84
+ cs = "+-00+-00+-00+-0"
85
+ print(longest_repeated_substring(cs))
86
+
87
+ # This code is contributed by ita_c
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.4
2
+ Name: csdigit
3
+ Version: 0.1
4
+ Summary: Add a short description here!
5
+ Home-page: https://github.com/pyscaffold/pyscaffold/
6
+ Author: Wai-Shing Luk
7
+ Author-email: luk036@gmail.com
8
+ License: MIT
9
+ Project-URL: Documentation, https://pyscaffold.org/
10
+ Platform: any
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python
13
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
14
+ License-File: LICENSE.txt
15
+ Requires-Dist: importlib-metadata; python_version < "3.9"
16
+ Provides-Extra: testing
17
+ Requires-Dist: setuptools; extra == "testing"
18
+ Requires-Dist: pytest; extra == "testing"
19
+ Requires-Dist: pytest-cov; extra == "testing"
20
+ Requires-Dist: pytest-benchmark; extra == "testing"
21
+ Requires-Dist: hypothesis; extra == "testing"
22
+ Dynamic: license-file
23
+
24
+ <!-- These are examples of badges you might want to add to your README:
25
+ please update the URLs accordingly
26
+
27
+ [![Built Status](https://api.cirrus-ci.com/github/<USER>/csdigit.svg?branch=main)](https://cirrus-ci.com/github/<USER>/csdigit)
28
+ [![Coveralls](https://img.shields.io/coveralls/github/<USER>/csdigit/main.svg)](https://coveralls.io/r/<USER>/csdigit)
29
+ [![PyPI-Server](https://img.shields.io/pypi/v/csdigit.svg)](https://pypi.org/project/csdigit/)
30
+ [![Conda-Forge](https://img.shields.io/conda/vn/conda-forge/csdigit.svg)](https://anaconda.org/conda-forge/csdigit)
31
+ [![Monthly Downloads](https://pepy.tech/badge/csdigit/month)](https://pepy.tech/project/csdigit)
32
+ [![Twitter](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Twitter)](https://twitter.com/csdigit)
33
+ -->
34
+
35
+ [![Project generated with PyScaffold](https://img.shields.io/badge/-PyScaffold-005CA0?logo=pyscaffold)](https://pyscaffold.org/)
36
+ [![ReadTheDocs](https://readthedocs.org/projects/csdigit/badge/?version=latest)](https://csdigit.readthedocs.io/en/latest/)
37
+ [![codecov](https://codecov.io/gh/luk036/csdigit/branch/main/graph/badge.svg?token=B8UXKlkDsc)](https://codecov.io/gh/luk036/csdigit)
38
+
39
+ # 🔄 csdigit
40
+
41
+ > Canonical Signed Digit Conversion in Python
42
+
43
+ A Canonical Signed Digit (CSD) is a specific form of signed-digit representation of numbers. In the context of CSD, each digit is constrained to a value of -1, 0, or 1, and no two consecutive digits are permitted to be non-zero. This representation has the advantage of being unique and having a minimal number of non-zero digits. CSD is frequently employed in digital signal processing applications, such as filter design, due to its capacity for the efficient implementation of arithmetic operations through the use of straightforward adders and subtractors. The number of adders and subtracters necessary to implement a CSD coefficient is equal to the number of non-zero digits in the library, minus one.
44
+
45
+ The objective of this library is to facilitate the conversion of numbers between decimal format and a special representation known as Canonical Signed Digit (CSD). CSD is a method of representing numbers using a mere three symbols: The symbols "0," "+," and "-" are used. It is particularly advantageous in specific domains within computer science and digital signal processing.
46
+
47
+ The primary objective of this library is to provide the necessary functions for the conversion of decimal numbers to CSD format and vice versa. The library accepts decimal numbers in their standard form (e.g., 28.5 or -0.5) and converts them to CSD strings (e.g., "+00-00.+" or "0.-"). It is also capable of performing the inverse operation, transforming CSD strings into decimal numbers.
48
+
49
+ The library contains a number of functions, each with a specific role.
50
+
51
+ 1. to_csd: This function takes a decimal number and the number of decimal places desired, and outputs a CSD string. To illustrate, the function can be used to convert the decimal number 28.5 to the CSD string "+00-00.+0," with two decimal places.
52
+
53
+ 2. to_csd_i: This function is analogous to to_csd, but it is designed for use with integers. The function converts whole numbers to CSD format, omitting the decimal point.
54
+
55
+ 3. The functions to_decimal_using_pow and to_decimal perform the inverse of the to_csd function. They accept a CSD string as input and return a decimal number.
56
+
57
+ 4. The to_csdnnz function is a variant of the to_csd function that allows the user to specify the maximum number of non-zero digits in the result.
58
+
59
+ The library fulfills its intended function through a sequence of mathematical operations and logical tests. In order to effect a conversion from decimal to CSD, the system employs the use of powers of 2 in order to ascertain which of the three symbols (+, -, or 0) is to be used at each position within the CSD string. The algorithm then performs repeated divisions of the input number by two and compares the result to specific thresholds to determine the appropriate symbol to use.
60
+
61
+ In order to perform the conversion from CSD to decimal, the algorithm proceeds by multiplying the running total by 2 and then adding, subtracting, or performing no further action based on the value of the symbol in the CSD string. This is done for each symbol in the string, where the symbol values are +, -, or 0. A distinct logic is employed for the integral and fractional parts, respectively.
62
+
63
+ Furthermore, the library incorporates error-checking mechanisms to guarantee the exclusive utilisation of valid CSD symbols. It also furnishes comprehensive documentation and illustrative examples for each function, thus facilitating user comprehension of the operational procedures.
64
+
65
+ In conclusion, this library offers a comprehensive set of tools for working with CSD representations, facilitating the conversion between decimal and CSD formats in a variety of ways.
66
+
67
+ ## Used By
68
+
69
+ [multiplierless](https://github.com/luk036/multiplierless)
70
+
71
+ ## 👀 See also
72
+
73
+ - [csd-rs](https://luk036.github.io/csd-rs)
74
+ - [csd-cpp](https://luk036.github.io/csd-cpp)
75
+
76
+ <!-- pyscaffold-notes -->
77
+
78
+ ## 👉 Note
79
+
80
+ This project has been set up using PyScaffold 4.5. For details and usage
81
+ information on PyScaffold see https://pyscaffold.org/.