bnum.html


001| ####################################################################################################
002| from sys import argv
003| from os import path
004| from time import perf_counter_ns
005| from math import log2
006| from decimal import Decimal, getcontext
007| from goodies import KWARG, typename
008| from files import linefile
009| ####################################################################################################
010| #TODO: Addition
011| #TODO: Scalar multiplication
012| #TODO: Better precision handling
013| ####################################################################################################
014| BasePath = r'C:\CJS\prj\Python\ws'
015| 
016| BinaryFractionsSize = 2500
017| 
018| 
019| ####################################################################################################
020| ## Multiplication Table
021| ##------------------------------------------------------------------------------------------------##
022| '''Generate two-byte little endian bytes object from integer.'''
023| itobs = lambda n: bytes(reversed(divmod(n,256)))
024| 
025| ##------------------------------------------------------------------------------------------------##
026| MulTable = [[itobs(a*b) for b in range(256)] for a in range(256)]
027| 
028| ##================================================================================================##
029| def demo_mul_table ():
030|     '''Show off some byte multiplications.'''
031| 
032|     print(f'{MulTable[0x00][0x00] = }')
033|     print(f'{MulTable[0x01][0x01] = }')
034|     print(f'{MulTable[0x02][0x02] = }')
035|     print(f'{MulTable[0x2a][0x2a] = }')
036|     print(f'{MulTable[0x45][0x67] = }')
037|     print(f'{MulTable[0x80][0x80] = }')
038|     print(f'{MulTable[0xAB][0xCD] = }')
039|     print(f'{MulTable[0xff][0xff] = }')
040|     print(f'')
041| 
042| 
043| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
044| class BFracs (list):
045|     """Binary Fractions list.
045| 
045| Auto-Generate a list object with N binary fractions.
045| E.G.
045|     [0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, ...]
045| 
045| Each list member is a tuple (dec_num, digits) where the first item is the
045| fraction as a Python Decimal instance and the second item is the fraction
045| as a tuple of integer value digits.
045| 
045| Static Methods:
045|     decimal_to_digits       -convert Decimal to full-size tuple
045| 
045| Methods:
045|     digits                  -only the digits
045|     values                  -only the Decimals
045|     save                    -save fraction digits to file as strings
045|     dump                    -save list values to file (as strings)
045| """

046|     @staticmethod
047|     def decimal_to_digits (dec_num:Decimal) -> tuple[int]:
048|         '''Convert Decimal to full-size tuple.'''
049| 
050|         sgn,ds,ex = dec_num.as_tuple()
051|         assert ex <= 0, ValueError(f'Unexpected positive Decimal exponent: {ex}')
052| 
053|         # if exponent is zero, return the tuple as is...
054|         if ex == 0:
055|             return (dec_num, ds)
056| 
057|         # Otherwise, add zeros as necessary...
058|         padding = (0,)*(1 + (abs(ex)-len(ds)))
059| 
060|         # And return with padding...
061|         return (dec_num, padding+ds)
062| 
063|     def __init__ (self, N):
064|         '''Generate N binary fractions. [0.5, 0.25, 0.125, 0.0625, ...]'''
065|         ctx = getcontext()
066|         ctx.prec = N + 1
067|         ctx.capitals = 0
068| 
069|         # Start with the first binary fraction...
070|         b = Decimal('0.5')
071| 
072|         # Add the first binary fraction...
073|         self.append(self.decimal_to_digits(b))
074| 
075|         # Build the list by progressive division by 2...
076|         for ix in range(N):
077|             b /= 2
078|             self.append(self.decimal_to_digits(b))
079| 
080|     def digits (self):
081|         '''Return a list with only the digits.'''
082|         return [digs for bf,digs in self]
083| 
084|     def values (self):
085|         '''Return a list with only the Decimal values.'''
086|         return [bf for bf,digs in self]
087| 
088|     def save (self, fname='bfracs.list', fpath=BasePath):
089|         '''Save fraction digits to file (as strings).'''
090| 
091|         # Open a linefile...
092|         fn = path.join(fpath,fname) if fpath else fname
093|         fo = linefile(fn)
094|         print(f'opened: {fn}')
095| 
096|         # Write fractions as strings of digits...
097|         for bf,digs in self:
098|             fo.add(''.join(str(d) for d in digs))
099|         fo.add()
100| 
101|         # Save file...
102|         fo.save()
103|         print(f'wrote: {fn}')
104|         print()
105| 
106|     def dump (self, fname='bfracs.out', fpath=BasePath):
107|         '''Dump self.values to file.'''
108| 
109|         # Open a file...
110|         fn = path.join(fpath, fname) if fpath else fname
111|         fo = linefile(fn)
112|         print(f'opened: {fn}')
113| 
114|         # Write fraction tuples (as strings)...
115|         for ix,n in enumerate(self, start=1):
116|             fo.add(f'{ix:4d}: {n!s}')
117| 
118|         # Save file...
119|         fo.save()
120|         print(f'wrote: {fn}')
121|         print()
122| 
123|     def __repr__ (self):
124|         '''Debug self string.'''
125|         return f'<{typename(self)} len={len(self)} @{id(self):08x}>'
126| 
127|     def __str__ (self):
128|         '''Print self string.'''
129|         s = '' if len(self)==1 else 's'
130|         return f'{typename(self)} ({len(self)} fraction{s})'
131| 
132| ##================================================================================================##
133| def demo_binary_fractions (size=800, fpath=BasePath):
134|     '''Exercise BFracs class.'''
135| 
136|     # Generate a binary fractions list...
137|     bfs = BFracs(size)
138|     bfs.save(fpath=fpath)
139|     bfs.dump(fpath=fpath)
140| 
141|     # Return list...
142|     return bfs
143| 
144| 
145| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
146| class BNum:
147|     """\
147| BNum class - arbitrary precision base 256 number.
147| 
147| Properties:
147|     bs                      -bytes; base 256 binary value
147|     sign                    -int; number sign [+1, -1]
147|     dp                      -int; decimal point; number of whole bytes
147|     prec                    -int; precision
147|     text                    -str: original input text
147|     whole                   -str: integer part of input text
147|     fract                   -str: fraction part of input text
147|     nval                    -int: from whole part of input text
147| 
147| Methods:
147|     str(obj)                -str; print string
147|     repr(obj)               -str; debug string
147|     bytes(obj)              -bytes; self.bs (!)
147|     bool(obj)               -bool; True if 0 < sum(self)
147|     int(obj)                -int; as integer value (truncates fraction)
147|     float(obj)              -float; as floating point value
147|     obj[ix]                 -int; indexed byte (as integer value)
147|     len(obj)                -int; number of bytes in self.bs
147|     byte in obj             -bool; byte in self.bs
147|     iter(obj)               -iterator over self.bs
147|     reversed(obj)           -reversed self.bs
147| 
147|     _generate_fraction      -bytes; parse a decimal string; return bytes
147|     _fraction_string        -list[str]; convert self to a string
147|     _type_check             -BNum; ensure OTHER is a BNum object
147|     _multiply_byte_strings  -bytes; multiply byte strings
147| 
147| Static Methods:
147|     from_bytes (bs, dp, sign)
147| 
147| """

148|     '''List of Decimal binary fractions (-powers of 2).'''
149|     BinaryFractions = BFracs(BinaryFractionsSize)
150| 
151|     '''Handy Dandy Decimal Zero.'''
152|     Zero = Decimal(0)
153| 
154|     def __init__ (self, number='0.0', precision=None, verbose=False):
155|         '''Create a new BNum instance.'''
156|         # Convert int or float to string...
157|         if isinstance(number,int) or isinstance(number,float):
158|             number = str(number)
159| 
160|         # Initialize instance...
161|         self.text = number.strip()                      # input text
162|         self.whole = self.text                          # whole text (assumption for now)
163|         self.fract = ''                                 # fraction text (ditto)
164|         self.sign = +1                                  # Number sign
165|         self.dp = 0                                     # Decimal point (# whole bytes)
166|         self.bs = bytes()                               # Base 256 FP number
167|         self.verbose = verbose
168|         self.prec = -1 if precision is None else precision
169| 
170|         # Empty string same as zero...
171|         if len(self.text) == 0:
172|             self.text = '0.0'
173| 
174|         # Ignore and remove leading plus sign...
175|         if self.text.startswith('+'):
176|             self.text.pop(0)
177| 
178|         # Handle leading minus sign...
179|         elif self.text.startswith('-'):
180|             self.sign = -1
181|             self.text.pop(0)
182| 
183|         # If decimal point, split into whole and fraction parts...
184|         if '.' in self.text:
185|             self.whole, self.fract = self.text.split('.')
186| 
187|         if self.prec < 0:
188|             self.prec = len(self.fract)
189| 
190|         # Convert whole string to bytes...
191|         self.nval = int(self.whole)
192|         if self.nval == 0:
193|             self.dp = 1
194|         else:
195|             self.dp = int(log2(self.nval) / 8) + 1
196|         # Bytes of the whole part...
197|         bwhole = self.nval.to_bytes(self.dp, 'big', signed=False)
198| 
199|         # Convert fraction string to bytes...
200|         bfract = self._generate_fraction()
201|         self.bs = bwhole + bfract
202| 
203|         if self.verbose:
204|             print(f'{self.text = }')
205|             print(f'{self.whole = }')
206|             print(f'{self.fract = }')
207|             print(f'{self.prec = }')
208|             print(f'{self.sign = }')
209|             print(f'{self.dp = }')
210|             print(f'{len(self) = }')
211|             print(f'{self.bs = }')
212|             print()
213| 
214|     def _generate_fraction (self) -> bytes:
215|         '''Function to parse a decimal string and return bytes.'''
216|         n = Decimal(f'0.{self.fract}')
217|         curr = 0
218|         bits = []
219|         for ix,bf in enumerate(t[0] for t in self.BinaryFractions):
220|             if n <= self.Zero:
221|                 break
222|             if bf <= n:
223|                 n -= bf
224|                 bits.append(1)
225|             else:
226|                 bits.append(0)
227| 
228|         buf = []
229|         while 0 < len(bits):
230|             bval = 0
231|             for bx in range(8):
232|                 bit = bits.pop(0) if 0 < len(bits) else 0
233|                 bval <<= 1
234|                 bval |= bit
235|             buf.append(bval)
236| 
237|         return bytes(buf)
238| 
239|     def _fraction_string (self) -> list[str]:
240|         '''Function to convert binary fraction to a string.'''
241|         bs = self.bs[self.dp:]
242|         fs = iter(self.BinaryFractions)
243| 
244|         # Fine the fraction parts (one bits)...
245|         parts = []
246|         for b in bs:
247|             mask = 0x80
248|             for bit in range(8):
249|                 try:
250|                     bnum = next(fs)
251|                 except StopIteration:
252|                     break
253|                 if b &  mask:
254|                     parts.append(bnum[1])
255|                 mask >>= 1
256| 
257|         # Check for zero...
258|         if len(parts) == 0:
259|             return '0'
260| 
261|         # Initialize the output...
262|         buf = list(parts[-1])
263| 
264|         def add_2_buf (ds):
265|             carry = 0
266|             for ix in reversed(range(len(ds))):
267|                 val = buf[ix] + ds[ix] + carry
268|                 if val < 10:
269|                     carry = 0
270|                 else:
271|                     val -= 10
272|                     carry = 1
273|                 buf[ix] = val
274|             if carry:
275|                 raise ValueError(f'CONVERSION OVERFLOW!')
276| 
277|         # Add other fraction parts to output...
278|         for part in reversed(parts[0:-1]):
279|             add_2_buf(part)
280| 
281|         return [str(d) for d in buf[1:]]
282| 
283|     def _type_check (self, other):
284|         '''Ensure OTHER is a BNum object.'''
285|         if isinstance(other,type(self)):
286|             return other
287|         if isinstance(other,int) or isinstance(other,float):
288|             return BNum(str(other))
289|         ValueError(f'{other!r} is not a {typename(self)}')
290| 
291|     def _multiply_byte_strings (self, bs1:bytes, bs2:bytes) -> bytes:
292|         '''Multiply byte strings. (ATTN: rework to eliminate the reversed?)'''
293|         #print(f'multiply({bs1.hex(".")}, {bs2.hex(".")})')
294| 
295|         # Accumulator...
296|         terms = {ix:0 for ix in range(len(bs1) + len(bs2))}
297| 
298|         # Generate Cartesian products...
299|         for ix1,b1 in enumerate(reversed(bs1)):
300|             for ix2,b2 in enumerate(reversed(bs2)):
301|                 res = MulTable[b1][b2]
302|                 terms [ix1+ix2] += res[0]
303|                 terms [ix1+ix2+1] += res[1]
304|                 #answer = [terms[ix] for ix in sorted(terms.keys())]
305|                 #print(f'multiply2.products[{b1},{b2}]: {answer}')
306| 
307|         # Ripple carry the terms...
308|         for ix in sorted(terms.keys()):
309|             carry,val = divmod(terms[ix], 256)
310|             if 0 < carry:
311|                 terms[ix] = val
312|                 terms[ix+1] += carry
313| 
314|         # Return the terms...
315|         answer = [terms[ix] for ix in sorted(terms.keys())]
316|         #print(f'multiply.exit: {answer}')
317|         return bytes(reversed(answer))
318| 
319|     def __bool__ (self):
320|         '''Return True if any bits set else False.'''
321|         return True if sum(self.bs) else False
322| 
323|     def __iter__ (self):
324|         '''Return an iterator over the number bytes.'''
325|         return iter(self.bs)
326| 
327|     def __len__ (self):
328|         '''Return the number of bytes used to store the number.'''
329|         return len(self.bs)
330| 
331|     def __getitem__ (self, ix):
332|         '''Return a byte by its index.'''
333|         return self.bs[ix]
334| 
335|     def __bytes__ (self):
336|         '''Return the number bytes.'''
337|         return self.bs
338| 
339|     def __reversed__ (self):
340|         '''Return the number bytes reversed.'''
341|         return reversed(self.bs)
342| 
343|     def __contains__ (self, item):
344|         '''Return True if the byte exists.'''
345|         return item in self.bs
346| 
347|     def __int__ (self):
348|         '''Return the whole part of the number as an integer.'''
349|         return int.from_bytes(self.bs[0:self.dp], 'big', signed=False)
350| 
351|     def __float__ (self):
352|         '''Return up to six of the leading bytes as a float.'''
353|         sgn = '-' if self.sign < 0 else '+'
354|         xw = ''.join(f'{b:02x}' for b in self.bs[:self.dp])
355|         xf = ''.join(f'{b:02x}' for b in self.bs[self.dp:])
356|         ex = 0
357|         return float.fromhex(f'{sgn}0x{xw}.{xf}p{ex}')
358| 
359|     def __add__ (self, other):
360|         '''Add this with other (typically another BNum).'''
361|         other = self._type_check(other)
362|         return BNum.from_bytes(bytes(1), 1, +1)
363| 
364|     def __radd__ (self, other):
365|         '''Add this with other (guaranteed to be not a BNum).'''
366|         other = self._type_check(other)
367|         return BNum.from_bytes(bytes(1), 1, +1)
368| 
369|     def __iadd__ (self, other):
370|         '''Add this with other (typically another BNum).'''
371|         other = self._type_check(other)
372|         return self
373| 
374|     def __mul__ (self, other):
375|         '''Multiply this by other (typically another BNum).'''
376|         other = self._type_check(other)
377|         bs = self._multiply_byte_strings(self.bs, other.bs)
378|         dp = self.dp + other.dp
379|         sgn = self.sign * other.sign
380|         prec = 2 * max(self.prec, other.prec)
381|         return BNum.from_bytes(bs, dp, sgn, precision=prec)
382| 
383|     def __rmul__ (self, other):
384|         '''Multiply this by other (guaranteed to be not a BNum).'''
385|         return self.__mul__(other)
386| 
387|     def __imul__ (self, other):
388|         '''Multiply this by other (typically another BNum).'''
389|         other = self._type_check(other)
390|         res = self._multiply_byte_strings(self.bs, other.bs)
391|         self.bs = res
392|         self.dp += other.dp
393|         self.sign *= other.sign
394|         self.prec = 2 * max(self.prec, other.prec)
395|         self.nval = int(self)
396|         self.whole = str(self.nval)
397|         self.fract = str(float(self)).partition('.')[2]
398|         self.text = f'{self.whole}.{self.fract}'
399|         return self
400| 
401|     # A BNum is a mutable object, so can't be used as an index key:
402|     __hash__ = None
403| 
404|     def __repr__ (self):
405|         '''Debug self string.'''
406|         sgn = '-' if self.sign < 0 else '+'
407|         return f'<{typename(self)} {sgn}{self.dp} @{id(self):08x}>'
408| 
409|     def __str__ (self):
410|         '''Print self string.'''
411|         sgn = '-' if self.sign < 0 else ('+' if 0 < self.sign else '')
412|         xf = ''.join(self._fraction_string())
413|         if 0 <= self.prec:
414|             xf = xf[0:self.prec]
415|         dot = '.' if 0 < len(xf) else ''
416|         return f'{sgn}{int(self)}{dot}{xf}'
417| 
418|     @staticmethod
419|     def from_bytes (bs:bytes, dp:int, sign:int, precision:int=-1):
420|         #print(f'from_bytes({bs.hex()}, {dp}, {sign})')
421|         n = BNum()
422|         n.bs = bs
423|         n.dp = dp
424|         n.sign = sign
425|         n.nval = int(n)
426|         n.whole = str(n.nval)
427|         n.fract = str(float(n)).partition('.')[2]
428|         n.prec = precision
429|         n.text = f'{n.whole}.{n.fract}'
430|         return n
431| 
432| ##================================================================================================##
433| def demo_binary_number (*args):
434|     '''Exercise the BNum class.'''
435| 
436|     s1 = args[0] if 0 < len(args) else '42.21'
437|     s2 = args[1] if 1 < len(args) else '4200.25'
438|     s3 = args[2] if 2 < len(args) else '4200000.0625'
439|     s4 = args[3] if 3 < len(args) else '11730.012345678901234567890123456789'
440| 
441|     def test (s):
442|         print('='*60)
443|         n = BNum(s, verbose=True)
444|         print(f'{n = !s}')
445|         print(f'{n = !r}')
446|         print(f'{int(n) = }')
447|         print(f'{float(n) = }')
448|         print()
449|         return n
450| 
451|     n0 = test('0')
452|     n1 = test(s1)
453|     n2 = test(s2)
454|     n3 = test(s3)
455|     n4 = test(s4)
456|     return (n0, n1, n2, n3, n4)
457| 
458| ##================================================================================================##
459| def test (*args):
460|     s1 = args[0] if 0 < len(args) else '0.999999999999999999'
461|     s2 = args[1] if 1 < len(args) else '4210'
462| 
463|     def prn (n):
464|         print(f'{n} {n!r}')
465|         print(f'{int(n) = }')
466|         print(f'{float(n) = }')
467|         print(f'{len(n) = }')
468|         print(f'{n.bs = }')
469|         print(f'{n.dp = }')
470|         print(f'{n.sign = }')
471|         print(f'{n.prec = }')
472|         print(f'{n.text = }')
473|         print(f'{n.whole = }')
474|         print(f'{n.fract = }')
475|         print()
476| 
477|     n1 = BNum(s1)
478|     n2 = BNum(s2)
479|     prn(n1)
480|     prn(n2)
481| 
482|     n0 = n1 * n2
483|     print()
484|     prn(n0)
485| 
486|     n2 *= n1
487|     print()
488|     prn(n2)
489| 
490|     return (n0, n1, n2)
491| 
492| ##================================================================================================##
493| def main (*args):
494|     rv = ()
495|     #rv = demo_mul_table()
496|     #rv = demo_binary_fractions(2000)
497|     #rv = demo_binary_number(*args)
498|     rv = test(*args)
499|     return rv
500| ####################################################################################################
501| if __name__ == '__main__':
502|     print(f'autorun: {argv[0]}')
503|     print()
504|     rv = main(*argv[1:])
505|     print()
506| ####################################################################################################
507|