dnum.html


001| """Decimal Numbers -- "infinite" precision numbers stored as individual digits.
001| 
001| Classes:
001|     dnum                    -"infinite" precision numbers
001|     trailingzeros (list)    -list subclass with "infinite" trailing zeros.
001| 
001| Data:
001|     Pi                      -good old Pi (3.141592653...)
001|     E                       -mysterious E (2.718281828...)
001|     GR                      -Golden Ratio (1.618,033,988,...)
001|     C                       -speed of light (299,792,458)
001|     C2                      -speed of light squared (89,875,517,873,681,764)
001|     Planck                  -6.626,070,15 e-34')
001| 
001| Functions:
001|     demo
001|     test
001|     main
001| 
001| (Note that Python's Decimal module does it better.)
001| """

002| ####################################################################################################
003| from sys import stdout
004| from itertools import zip_longest
005| from goodies import typename
006| ####################################################################################################
007| #!TODO! _divide_ is SLOW!
008| #!TODO? __floordiv__, __mod__, __divmod__
009| #!TODO? __pow__ (positive integer exponent only?)
010| #!TODO? log
011| #!TODO? square/cube
012| #!TODO? sqrt
013| #!TODO? trig (sin, cos, tan, etc)
014| #!TODO? rand
015| ####################################################################################################
016| Log = stdout
017| 
018| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
019| class trailingzeros (list):
020|     """Specialized list with "infinite" trailing zeros."""
021| 
022|     def compare (self, offset, divisor:list) -> bool:
023|         #print(f'{typename(self)}.compare({offset}, {divisor})', file=Log)
024|         rn = reversed(self[0:offset+len(divisor)])
025|         rd = reversed(divisor)
026|         pairs = reversed(list(zip_longest(rd, rn, fillvalue=0)))
027|         for a,b in pairs:
028|             if a < b:
029|                 return True
030|             if b < a:
031|                 return False
032|         return True
033| 
034|     def ltrim (self, value:int=0):
035|         #print(f'{typename(self)}.ltrim({value})', file=Log)
036|         for ix in range(len(self)):
037|             if self[ix]:
038|                 #print(f'{typename(self)}.ltrim: del[0:{ix}]', file=Log)
039|                 del self[0:ix]
040|                 break
041|         #print(file=Log)
042| 
043|     def __getitem__ (self, ix):
044|         """Override for x=list[ix]"""
045|         if isinstance(ix,int) and (len(self) <= ix):
046|             #print(f'{typename(self)}.getitem({ix}) => 0', file=Log)
047|             return 0
048| 
049|         if isinstance(ix,slice):
050|             width = ix.stop - (0 if ix.start is None else ix.start)
051|             #print(f'{typename(self)}.getitem({ix.start}:{ix.stop}:{ix.step};{width})', file=Log)
052|             retv = super().__getitem__(ix)
053|             if len(retv) < width:
054|                 retv.extend([0]*(width-len(retv)))
055|             #print(f'{typename(self)}.getitem => {retv}', file=Log)
056|             return retv
057| 
058|         #print(f'{typename(self)}.getitem({ix}:{typename(ix)})', file=Log)
059|         return super().__getitem__(ix)
060| 
061|     def __setitem__ (self, ix, value):
062|         """Override for list[ix] = x"""
063| 
064|         if isinstance(ix,int) and (len(self) <= ix):
065|             #print(f'{typename(self)}.setitem({ix}, {value})', file=Log)
066|             extra = 1 + (ix - len(self))
067|             self.extend([0]*extra)
068|             super().__setitem__(ix, value)
069|             return
070| 
071|         if isinstance(ix,slice):
072|             width = ix.stop - ix.start
073|             #print(f'{typename(self)}.setitem({ix.start}:{ix.stop}:{ix.step};{width}, {value})', file=Log)
074|             if len(self) <= ix.start:
075|                 extra = 1 + (ix.start - len(self)) + width
076|                 self.extend([0]*extra)
077|             super().__setitem__(ix, value)
078|             return
079| 
080|         #print(f'{typename(self)}.setitem({ix}, {value})', file=Log)
081|         super().__setitem__(ix, value)
082| 
083| 
084| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
085| class dnum:
086|     """\
086| Decimal Number class.
086| 
086| Arbitrary precision number stored as individual digits. Initialize with integer, float,
086| string, list of raw digits, or another dnum instance.
086| 
086| Global Properties:
086|     Pi              -dnum: pi to lots of digits
086|     E               -dnum: magical e to many digits
086|     C               -dnum: the speed of light
086|     C2              -dnum: the speed of light squared
086|     Planck          -dnum: the Planck unit
086| 
086| Class Properties:
086|     Base            - int: numeric base (default: 10)
086|     DivPrec         - int: number of extra digits in division (default: 8)
086|     ShowPlus        - bool: normally show plus sign on output (default: False)
086| 
086| Properties:
086|     digits          -list: digits of number (integer values from 0 to Base-1)
086|     sign            -int: +1 or -1
086|     dp              -int: number of whole digits
086|     wholelen        -int: number of whole digits (same as dp)
086|     fractlen        -int: number of decimal digits
086|     pm              -str: "+" or "-" (or "") depending on sign
086| 
086| Methods:
086|     count                   -int: count number of given digits
086|     incr, decr              -self: increment/decrement number (by one); work like odometers
086|     shiftleft               -self: shift digits left (in-place; keeps width; loses digits)
086|     shiftright              -self: shift digits right (in-place; keeps width; loses digits)
086|     rotateleft              -self: rotate digits left (in-place; keeps width)
086|     rotateright             -self: rotate digits right (in-place; keeps width)
086|     square                  -dnum: number squared
086|     cube                    -dnum: number cubed
086| 
086| Operators:
086|     str                     -str: return number as string (uses format with no spec)
086|     repr                    -str: debugging string
086|     format                  -str: formatted version
086|     [ix]                    -digit(s): index digits
086|     len                     -int: number of digits
086|     iter                    -iter: iterator over digits
086|     reversed                -list: digits reversed (reversed object)
086|     bytes                   -bytes: byte string of (raw) digits
086|     int                     -int: integer value
086|     float                   -float: float value (may lose precision)
086|     bool                    -bool: True (non-zero) or False (zero)
086|     in                      -bool: test for a digit somewhere in the number
086|     == != <= < > >=         -bool: relational operators
086|     abs                     -dnum: absolute value of number
086|     unary + -               -dnum: unary plus returns a copy; unary minus flips sign
086|     unary ~                 -dnum: invert number
086|     ops + - * /             -dnum: basic binary math operations add, sub, mul, div
086|     ops += -= *= /=         -dnum: in-place versions of basic binary math ops
086|     ops << >> <<= >>=       -dnum: left and right shift with in-place versions
086|     ops & | ^               -dnum: bitwise and, or, xor
086|     trunc, floor, ceil      -dnum: support for functions from math module
086| 
086| Utility Methods:
086|     _trim_zeros             -Remove any leading whole or trailing fraction zeros
086|     _coerce_type            -Ensure that other is a dnum object.
086|     _need_an_integer        -Ensure other is an integer value.
086|     _combine_digits_pair    -Combine digits of self and other with a function.
086|     _process_list           -Convert a list of items to valid list of digits.
086|     _add_                   -Add two dnum objects. Returns tuple (digits, dp)
086|     _sub_                   -Subtract two dnum objects. Returns tuple (digits, dp)
086|     _multiply_              -Multiply two dnum objects
086|     _divide_                -Divide two dnum objects. self÷other (self/other)
086| """

087|     Base = 10
088|     DivPrec = 8
089|     ShowPlus = False
090| 
091|     def __init__ (self, initial_value=None, dp=None):
092|         """\
092| New dnum instance.
092| 
092| Initialize with no value, explicit None, an empty string, any form of zero
092| string (e.g. "0" or "0.00"), or the integer or float value zero. All create
092| a zero dnum with a single (zero) digit, a positive sign, and DP set to 1.
092| Other (non-zero) intializations are:
092| 
092|     -an integer or float value
092|     -a numeric string value
092|     -a list or tuple of raw digits; values must be from 0 to Base-1
092|     -any iterable object (other than string) with valid values
092|     -another dnum instance; *copies* digits, DP, and sign
092| 
092| Notes:
092|     -initialization trims leading and trailing zeros.
092|     -iterables may contain a leading "+"/"-" and single "."
092| """

093|         if isinstance(initial_value,type(self)):
094|             self.digits = list(initial_value.digits)
095|             self.dp = initial_value.dp
096|             self.sign = initial_value.sign
097|             return
098| 
099|         # Handle None...
100|         if (initial_value is None) or (initial_value == '') or (initial_value == 0):
101|             instr = ['0']
102|             self.digits = [0]
103|             self.dp = 1
104|             self.sign = +1
105|             return
106| 
107|         # Handle list/tuple input...
108|         if isinstance(initial_value,list) or isinstance(initial_value,tuple):
109|             buf,dp,sgn = self._process_list(initial_value)
110|             self.digits = buf
111|             self.dp = dp
112|             self.sign = sgn
113|             self._trim_zeros()
114|             return
115| 
116|         # Handle numeric input...
117|         if isinstance(initial_value,int) or isinstance(initial_value,float):
118|             instr = list(str(initial_value))
119|         # Expecting a string...
120|         else:
121|             if not isinstance(initial_value,str):
122|                 # Handle other iterable inputs...
123|                 try:
124|                     items = iter(initial_value)
125|                     buf,dp,sgn = self._process_list(initial_value)
126|                     self.digits = buf
127|                     self.dp = dp
128|                     self.sign = sgn
129|                     self._trim_zeros()
130|                     return
131|                 except:
132|                     pass
133|                 raise TypeError(f'Invalid initialization type: {typename(initial_value)}')
134| 
135|             # Remove convenience characters...
136|             stripfunc = lambda x: x not in [',', '_']
137|             instr = list(filter(stripfunc, initial_value))
138| 
139|         # Determine the sign...
140|         self.sign = +1 # assume number is positive
141|         if instr[0] in ['+','-']:
142|             if instr[0] == '-':
143|                 self.sign = -1
144|             instr.pop(0)
145| 
146|         # Force a leading zero if necessary...
147|         if instr[0] == '.':
148|             instr.insert(0, '0')
149|         if instr[-1] == '.':
150|             instr.append('0')
151| 
152|         # Determine the decimal point...
153|         if '.' in instr:
154|             self.dp = instr.index('.')
155|             instr.pop(self.dp)
156|         else:
157|             self.dp = len(instr)
158| 
159|         # Process the digits...
160|         self.digits = []
161|         for d in instr:
162|             n = int(d, base=0)
163|             self.digits.append(n)
164| 
165|         # Trim off any leading/trailing zeros...
166|         self._trim_zeros()
167| 
168|     # ============ Number Properties ============
169|     @property
170|     def wholelen (self) -> int:
171|         '''Return length of whole-part digits.'''
172|         return self.dp
173| 
174|     @property
175|     def fractlen (self) -> int:
176|         '''Return length of fraction-part digits.'''
177|         return (len(self) - self.dp)
178| 
179|     # ============ Decimal Number Methods ============
180|     def count (self, digit:int) -> int:
181|         '''Count number of given digit in digits.'''
182|         return self.digits.count(digit)
183| 
184|     def incr (self, digit_index:int=0):
185|         '''Increment number by one.'''
186|         digx = (self.dp - 1) - digit_index
187|         # Increment digit (if in range)...
188|         if 0 <= digx < len(self):
189|             self.digits[digx] += 1
190|         self._ripple_carry()
191|         return self
192| 
193|     def decr (self, digit_index:int=0):
194|         '''Decrement number by one.'''
195|         digx = (self.dp - 1) - digit_index
196|         # Decrement digit (if in range)...
197|         if 0 <= digx < len(self):
198|             self.digits[digx] -= 1
199|         self._ripple_carry()
200|         return self
201| 
202|     def shiftleft (self, n_digits:int):
203|         '''Shift digits left (in-place). Preserves size but not digits or DP.'''
204|         n = self._need_an_integer(n_digits, 'ShiftL')
205|         # Shift self digits...
206|         del self.digits[:n]
207|         self.digits.extend([0]*n)
208|         #self._trim_zeros()
209|         return self
210| 
211|     def shiftright (self, n_digits:int):
212|         '''Shift digits right (in-place). Preserves size but not digits or DP.'''
213|         n = self._need_an_integer(n_digits, 'ShiftR')
214|         del self.digits[-n:]
215|         self.digits[0:0] = [0]*n
216|         #self._trim_zeros()
217|         return self
218| 
219|     def rotateleft (self, n_digits:int):
220|         '''Rotate digits left (in-place). Preserves size but not digits or DP.'''
221|         n = self._need_an_integer(n_digits, 'RotateL')
222|         head = self.digits[:n]
223|         self.digits.extend(head)
224|         del self.digits[:n]
225|         #self._trim_zeros()
226|         return self
227| 
228|     def rotateright (self, n_digits:int):
229|         '''Rotate digits right (in-place). Preserves size but not digits or DP.'''
230|         n = self._need_an_integer(n_digits, 'RotateR')
231|         tail = self.digits[-n:]
232|         self.digits[0:0] = tail
233|         del self.digits[-n:]
234|         #self._trim_zeros()
235|         return self
236| 
237|     def square (self):
238|         '''Return self squared.'''
239|         return self * self
240| 
241|     def cube (self):
242|         '''Return self cubed.'''
243|         return self * self * self
244| 
245|     # ============ String Representations ============
246|     @property
247|     def pm (self) -> str:
248|         '''Return "+", "-", or "", depending on sign.'''
249|         return '-' if self.sign < 0 else ('+' if 0 < self.sign else '')
250| 
251|     def __repr__ (self) -> str:
252|         '''Debugging string representation.'''
253|         return f'<{typename(self)} {self.pm}{self.dp}/{len(self)} @{id(self):08x}>'
254| 
255|     def __str__ (self) -> str:
256|         '''Return the number as a string.'''
257|         return self.__format__('')
258| 
259|     def __format__ (self, fspec:str) -> str:
260|         """\
260| Format number according to format-spec: "[>|<][+|-][,][n][.m]"
260| All fields optional but must appear in correct order if supplied.
260| 
260|     > or <      -right or left justify (right is default)
260|                  only applies if number shorter than field width
260| 
260|     + or -      -plus forces display of "+"; minus does nothing
260|                  (the minus is included just for balance)
260| 
260|     ,           -insert commas in output string
260|                  every three digits in whole and fraction parts
260| 
260|     n.m         -total fields width / decimal digits
260|                  if N not supplied, width is unlimited
260|                  if M not supplied, decimal digits are unlimited
260|                  if N is 0, output is an empty string!
260|                  if M is 0, decimal digits are suppresse
260| 
260| Returns a string (obviously).
260| """

261|         specs = list(fspec)
262| 
263|         # Justify flag...
264|         just = 0
265|         if (0 < len(specs)) and (specs[0] in ['>', '<']):
266|             if specs.pop(0) == '<':
267|                 just = 1
268| 
269|         # Plus/minus flag...
270|         show_plus = 0
271|         if (0 < len(specs)) and (specs[0] in ['-', '+']):
272|             if specs.pop(0) == '+':
273|                 show_plus = 1
274| 
275|         # Commas flag...
276|         use_commas = 0
277|         if (0 < len(specs)) and (specs[0] == ','):
278|             specs.pop(0)
279|             use_commas = 1
280| 
281|         # Field widths...
282|         width,fract = None,None # no restriction
283|         if 0 < len(specs):
284|             if '.' in specs:
285|                 dot = specs.index('.')
286|                 lhs = specs[:dot]
287|                 rhs = specs[dot+1:]
288|                 width = int(''.join(lhs)) if 0<len(lhs) else None
289|                 fract = int(''.join(rhs)) if 0<len(rhs) else None
290|             else:
291|                 width = int(''.join(specs))
292| 
293|         # Format output string...
294|         digs = [str(d) for d in self.digits]
295| 
296|         # Format decimal digits...
297|         if self.dp < len(digs):
298|             # Trim fraction digits if requested...
299|             if fract is not None:
300|                 del digs[self.dp+fract:]
301| 
302|             if use_commas:
303|                 cx = self.dp + 3
304|                 while cx < len(digs):
305|                     digs.insert(cx, ',')
306|                     cx += 4
307| 
308|             # Insert decimal point...
309|             digs.insert(self.dp, '.')
310| 
311|             # Ensure a leading zero...
312|             if self.dp == 0:
313|                 digs.insert(0, '0')
314| 
315|         # Handle adding commas...
316|         if use_commas:
317|             # Index the decimal point for whole.fract split...
318|             dpx = digs.index('.') if '.' in digs else len(digs)
319|             cx = dpx - 3
320|             while 0 < cx < len(digs):
321|                 digs.insert(cx, ',')
322|                 cx -= 3
323| 
324|         # Handle sign...
325|         if self.sign < 0:
326|             digs.insert(0, '-') # can't turn this off
327|         elif 0 < self.sign:
328|             if self.ShowPlus or show_plus:
329|                 digs.insert(0, '+')
330| 
331|         # Handle field width and justification...
332|         if width is not None:
333|             del digs[width:]
334|             if len(digs) < width:
335|                 if just:
336|                     digs.extend([' ']*(width-len(digs)))
337|                 else:
338|                     digs[0:0] = [' ']*(width-len(digs))
339| 
340|         return ''.join(digs)
341| 
342|     # ============ List Operations ============
343|     def __bool__ (self) -> bool:
344|         '''Return True if any non-zero digits else False.'''
345|         return True if 0 < sum(self.digits) else False
346| 
347|     def __int__ (self) -> int:
348|         '''Return integer value.'''
349|         s = ''.join(str(d) for d in self.digits[0:self.dp])
350|         return int(f'{self.pm}{s}', base=self.Base)
351| 
352|     def __float__ (self) -> float:
353|         return float(str(self))
354| 
355|     def __bytes__ (self) -> bytes:
356|         '''Return the digits as a byte string.'''
357|         return bytes(self.digits)
358| 
359|     def __reversed__ (self) -> reversed:
360|         '''Return the digits reversed.'''
361|         return reversed(self.digits)
362| 
363|     def __contains__ (self, digit:int) -> bool:
364|         '''Return True if digit exists.'''
365|         return digit in self.digits
366| 
367|     def __len__ (self) -> int:
368|         '''Return the number of digits.'''
369|         return len(self.digits)
370| 
371|     def __iter__ (self) -> iter:
372|         '''Return an iterator over the digits.'''
373|         return iter(self.digits)
374| 
375|     def __getitem__ (self, ix) -> int:
376|         '''Return an indexed digit.'''
377|         return self.digits[ix]
378| 
379|     def __setitem__ (self, ix, digit:int):
380|         '''Set an indexed digit.'''
381|         self.digits[ix] = digit
382| 
383|     # ============ Relational Operators ============
384|     def __eq__ (self, other) -> bool:
385|         '''Called for obj1 == obj2. Return a boolean.'''
386|         other = self._coerce_type(other, 'Comparison')
387|         # Easy stuff...
388|         if self.sign != other.sign: return False
389|         if self.dp != other.dp: return False
390|         # Compare...
391|         res,_,_ = self._sub_(other)
392|         return True if sum(res)==0 else False
393| 
394|     def __lt__ (self, other) -> bool:
395|         '''Called for obj1 < obj2. Return a boolean.'''
396|         other = self._coerce_type(other, 'Comparison')
397|         # Compare...
398|         res,dp,sgn = self._sub_(other)
399|         if sum(res) == 0: return False
400|         return True if sgn < 0 else False
401| 
402|     def __gt__ (self, other) -> bool:
403|         '''Called for obj1 > obj2. Return a boolean.'''
404|         other = self._coerce_type(other, 'Comparison')
405|         # Compare...
406|         res,dp,sgn = self._sub_(other)
407|         if sum(res) == 0: return False
408|         return True if 0 < sgn else False
409| 
410|     def __ne__ (self, other) -> bool:
411|         '''Called for obj1 != obj2. Return a boolean.'''
412|         return not self.__eq__(other)
413| 
414|     def __le__ (self, other) -> bool:
415|         '''Called for obj1 <= obj2. Return a boolean.'''
416|         return not self.__gt__(other)
417| 
418|     def __ge__ (self, other) -> bool:
419|         '''Called for obj1 >= obj2. Return a boolean.'''
420|         return not self.__lt__(other)
421| 
422|     # ============ Unary Operators ============
423|     def __abs__ (self):
424|         '''Implement abs() function.'''
425|         retv = dnum(self)
426|         retv.sign = +1
427|         retv._trim_zeros()
428|         return retv
429| 
430|     def __pos__ (self):
431|         '''Implement unary plus sign.'''
432|         retv = dnum(self)
433|         retv._trim_zeros()
434|         return retv
435| 
436|     def __neg__ (self):
437|         '''Implement unary minus sign.'''
438|         retv = dnum(self)
439|         retv.sign = -self.sign
440|         retv._trim_zeros()
441|         return retv
442| 
443|     def __invert__ (self):
444|         '''Invert. Return a number that sums with self to -1.'''
445|         retv = dnum(self)
446|         if retv.sign < 0:
447|             retv.decr()
448|             retv.sign = +1
449|         else:
450|             retv.incr()
451|             retv.sign = -1
452|         return retv
453| 
454|     def __trunc__ (self):
455|         '''Implementation for math.trunc function.'''
456|         retv = dnum(self)
457|         del retv.digits[self.dp:]
458|         return retv
459| 
460|     def __floor__ (self):
461|         '''Implementation for math.floor function.'''
462|         retv = dnum(self)
463|         del retv.digits[self.dp:]
464|         # If negative with a fractional part...
465|         frac = sum(self.digits[self.dp:])
466|         if (self.sign < 0) and (0 < frac):
467|             # Floor is next larger negative integer...
468|             retv.incr()
469|         return retv
470| 
471|     def __ceil__ (self):
472|         '''Implementation for math.ceil function.'''
473|         retv = dnum(self)
474|         del retv.digits[self.dp:]
475|         # If positive with a fractional part...
476|         frac = sum(self.digits[self.dp:])
477|         if (0 < self.sign) and (0 < frac):
478|             # Ceiling is next larger positive integer...
479|             retv.incr()
480|         return retv
481| 
482|     def __round__(self, ndigits:int=None):
483|         '''Implementation for built-in round function.'''
484| 
485|         # If ndigits not supplied, sames as trunc()
486|         if ndigits is None:
487|             return self.__trunc__()
488| 
489|         def up_or_down (digs:list) -> int:
490|             '''Round up (+1), down (-1), even (0).'''
491|             if digs[0] < 5: return -1
492|             if 5 < digs[0]: return +1
493|             # First digit was 5, so...
494|             for d in digs[1:]:
495|                 if 0 < d: return +1
496|             return 0
497| 
498|         # Round up or down...
499|         retv = dnum(self)
500|         nd = self._need_an_integer(ndigits, 'Round')
501|         if 0 <= nd < self.fractlen:
502|             u_d = up_or_down(self.digits[self.dp+nd:])
503|             del retv.digits[self.dp+nd:]
504|             if 0 <= u_d:
505|                 retv.incr(-nd)
506|         return retv
507| 
508|     # ============ Addition ============
509|     def __add__ (self, other):
510|         '''Addition (RHS is other).'''
511|         other = self._coerce_type(other, 'Addition')
512|         if self.sign == other.sign:
513|             # ADD...
514|             res,dp = self._add_(other)
515|             # Copy LHS sign...
516|             sgn = self.sign
517|         else:
518|             # SUB...
519|             res,dp,sgn = self._sub_(other)
520|             # Flip sign if LHS is negative...
521|             if self.sign < 0:
522|                 sgn *= -1
523|         # Return result in new instance...
524|         retv = dnum()
525|         retv.digits = res
526|         retv.dp = dp
527|         retv.sign = sgn
528|         retv._trim_zeros()
529|         return retv
530| 
531|     def __radd__ (self, other):
532|         '''Addition (LHS is other).'''
533|         return self.__add__(other)
534| 
535|     def __iadd__ (self, other):
536|         '''In-Place Addition.'''
537|         other = self._coerce_type(other, 'Addition')
538|         if self.sign == other.sign:
539|             # ADD...
540|             res,dp = self._add_(other)
541|             # Copy LHS sign...
542|             sgn = self.sign
543|         else:
544|             # SUB...
545|             res,dp,sgn = self._sub_(other)
546|             # Flip sign if LHS is negative...
547|             if self.sign < 0:
548|                 sgn *= -1
549|         # Set self to result...
550|         self.digits = res
551|         self.dp = dp
552|         self.sign = sgn
553|         self._trim_zeros()
554|         return self
555| 
556|     # ============ Subtraction ============
557|     def __sub__ (self, other):
558|         '''Subtraction (RHS is other).'''
559|         other = self._coerce_type(other, 'Subtraction')
560|         if self.sign == other.sign:
561|             # SUB...
562|             res,dp,sgn = self._sub_(other)
563|             # Flip sign if LHS is negative...
564|             if self.sign < 0:
565|                 sgn *= -1
566|         else:
567|             # ADD...
568|             res,dp = self._add_(other)
569|             # Copy LHS sign...
570|             sgn = self.sign
571|         # Return result in new instance...
572|         retv = dnum()
573|         retv.digits = res
574|         retv.dp = dp
575|         retv.sign = sgn
576|         retv._trim_zeros()
577|         return retv
578| 
579|     def __rsub__ (self, other):
580|         '''Subtraction (LHS is other).'''
581|         other = self._coerce_type(other, 'Subtraction')
582|         return other.__sub__(self)
583| 
584|     def __isub__ (self, other):
585|         '''In-Place Subtraction.'''
586|         other = self._coerce_type(other, 'Subtraction')
587|         if self.sign == other.sign:
588|             # SUB...
589|             res,dp,sgn = self._sub_(other)
590|             # Flip sign if LHS is negative...
591|             if self.sign < 0:
592|                 sgn *= -1
593|         else:
594|             # ADD...
595|             res,dp = self._add_(other)
596|             # Copy LHS sign...
597|             sgn = self.sign
598|         # Set self to result...
599|         self.digits = res
600|         self.dp = dp
601|         self.sign = sgn
602|         self._trim_zeros()
603|         return self
604| 
605|     # ============ Multiplication ============
606|     def __mul__ (self, other):
607|         '''Multiplication (RHS is other).'''
608|         other = self._coerce_type(other, 'Multiplication')
609|         res = self._multiply_(other)
610|         # Return result in new instance...
611|         retv = dnum()
612|         retv.digits = res
613|         retv.sign = self.sign * other.sign
614|         retv.dp = len(res) - (self.fractlen + other.fractlen)
615|         retv._trim_zeros()
616|         return retv
617| 
618|     def __rmul__ (self, other):
619|         '''Multiplication (LHS is other).'''
620|         return self.__mul__(other)
621| 
622|     def __imul__ (self, other):
623|         '''In-Place Multiplication.'''
624|         other = self._coerce_type(other, 'Multiplication')
625|         res = self._multiply_(other)
626|         # Set self to result...
627|         self.sign *= other.sign
628|         self.dp = len(res) - (self.fractlen + other.fractlen)
629|         self.digits = res
630|         self._trim_zeros()
631|         return self
632| 
633|     # ============ Division ============
634|     def __truediv__ (self, other):
635|         '''Division (self is numerator; other is divisor).'''
636|         other = self._coerce_type(other, 'Division')
637|         res,dp,rem = self._divide_(other)
638|         # Return result in new instance...
639|         retv = dnum()
640|         retv.digits = [d for d in res if isinstance(d,int)]
641|         retv.dp = dp
642|         retv.sign = self.sign * other.sign
643|         retv._trim_zeros()
644|         return retv
645| 
646|     def __rtruediv__ (self, other):
647|         '''Division (LHS is other).'''
648|         other = self._coerce_type(other, 'Division')
649|         return other.__truediv__(self)
650| 
651|     def __itruediv__ (self, other):
652|         '''In-Place Division (self is numerator; other is divisor).'''
653|         other = self._coerce_type(other, 'Division')
654|         res,dp,rem = self._divide_(other)
655|         # Return result in new instance...
656|         self.digits = [d for d in res if isinstance(d,int)]
657|         self.dp = dp
658|         self.sign = self.sign * other.sign
659|         self._trim_zeros()
660|         return self
661| 
662|     # def __floordiv__ (self, other):
663|     # def __mod__ (self, other):
664|     # def __divmod__ (self, other):
665| 
666|     # ============ More Math ============
667|     # def __pow__ (self, other, modulo=None):
668| 
669|     # ============ Shift Operators ============
670|     def __lshift__ (self, other):
671|         '''Left Shift (RHS is count). Preserves precision; adjusts DP.'''
672|         n = self._need_an_integer(other, 'LShift')
673|         # Return result in new instance...
674|         retv = dnum(self)
675|         retv.digits.extend([0]*n)
676|         retv.dp += n
677|         retv._trim_zeros()
678|         return retv
679| 
680|     def __ilshift__ (self, other):
681|         '''In-Place Left Shift (RHS is count). Preserves precision; adjusts DP.'''
682|         n = self._need_an_integer(other, 'LShift')
683|         # Shift self digits...
684|         self.digits.extend([0]*n)
685|         self.dp += n
686|         self._trim_zeros()
687|         return self
688| 
689|     def __rshift__ (self, other):
690|         '''Right Shift (RHS is count). Preserves precision; effectively changes DP.'''
691|         n = self._need_an_integer(other, 'RShift')
692|         # Return result in new instance...
693|         retv = dnum(self)
694|         retv.digits[0:0] = [0]*n
695|         retv._trim_zeros()
696|         return retv
697| 
698|     def __irshift__ (self, other):
699|         '''In-Place Right Shift (RHS is count). Preserves precision; effectively changes DP.'''
700|         n = self._need_an_integer(other, 'RShift')
701|         # Return result in new instance...
702|         self.digits[0:0] = [0]*n
703|         self._trim_zeros()
704|         return self
705| 
706|     # ============ Bitwise Operators ============
707|     def __and__ (self, other):
708|         '''Bitwise AND (RHS is other).'''
709|         other = self._coerce_type(other, 'AND')
710|         res,dp = self._combine_digits_pair(other, lambda a,b: a&b)
711|         # Return result in new instance...
712|         retv = dnum()
713|         retv.digits = res
714|         retv.dp = dp
715|         retv.sign = self.sign if 0<(self.sign*other.sign) else -self.sign
716|         return retv
717| 
718|     def __rand__ (self, other):
719|         '''Bitwise AND (LHS is other).'''
720|         return self.__and__(other)
721| 
722|     def __iand__ (self, other):
723|         '''In-Place Bitwise AND (RHS is other).'''
724|         other = self._coerce_type(other, 'AND')
725|         res,dp = self._combine_digits_pair(other, lambda a,b: a&b)
726|         # Set self to result...
727|         self.digits = res
728|         self.sign = self.sign if 0<(self.sign*other.sign) else -self.sign
729|         self.dp = dp
730|         return self
731| 
732|     def __or__ (self, other):
733|         '''Bitwise OR (RHS is other).'''
734|         other = self._coerce_type(other, 'OR')
735|         res,dp = self._combine_digits_pair(other, lambda a,b: a|b)
736|         # Return result in new instance...
737|         retv = dnum()
738|         retv.digits = res
739|         retv.dp = dp
740|         retv.sign = self.sign #ATTN: ???
741|         retv._ripple_carry()
742|         return retv
743| 
744|     def __ror__ (self, other):
745|         '''In-Place Bitwise OR (LHS is other).'''
746|         return self.__and__(other)
747| 
748|     def __ior__ (self, other):
749|         '''Bitwise OR (RHS is other).'''
750|         other = self._coerce_type(other, 'OR')
751|         res,dp = self._combine_digits_pair(other, lambda a,b: a|b)
752|         # Set self to result...
753|         self.digits = res
754|         self.dp = dp
755|         self.sign = other.sign
756|         self._ripple_carry()
757|         return self
758| 
759|     def __xor__ (self, other):
760|         '''Bitwise XOR (RHS is other).'''
761|         other = self._coerce_type(other, 'XOR')
762|         res,dp = self._combine_digits_pair(other, lambda a,b: a^b)
763|         # Return result in new instance...
764|         retv = dnum()
765|         retv.digits = res
766|         retv.dp = dp
767|         retv.sign = self.sign if self.sign==other.sign else -self.sign
768|         retv._ripple_carry()
769|         return retv
770| 
771|     def __rxor__ (self, other):
772|         '''Bitwise XOR (LHS is other).'''
773|         return self.__and__(other)
774| 
775|     def __ixor__ (self, other):
776|         '''In-Place Bitwise XOR (RHS is other).'''
777|         other = self._coerce_type(other, 'XOR')
778|         res,dp = self._combine_digits_pair(other, lambda a,b: a^b)
779|         # Set self to result...
780|         self.digits = res
781|         self.dp = dp
782|         self.sign = self.sign if self.sign==other.sign else -self.sign
783|         self._ripple_carry()
784|         return self
785| 
786|     # ============ Utility Methods ============
787|     def _trim_zeros (self):
788|         """Remove any leading whole or trailing fraction zeros."""
789| 
790|         # Trim the whole part...
791|         while (self.digits[0]==0) and (1 < self.dp):
792|             self.digits.pop(0)
793|             self.dp -= 1
794| 
795|         # Trim the fraction part...
796|         while (self.digits[-1]==0) and (self.dp < len(self)):
797|             self.digits.pop()
798| 
799|         if not self:
800|             self.sign = +1
801| 
802|     def _ripple_carry (self) -> int:
803|         '''Ripple down digits and carry any over/under flow.'''
804|         carry = 0
805|         for ix in reversed(range(len(self.digits))):
806|             carry,digit = divmod(self.digits[ix]+carry, self.Base)
807|             self.digits[ix] = digit
808|         return carry
809| 
810|     def _coerce_type (self, other, label:str):
811|         """Ensure that other is a dnum object."""
812| 
813|         # Normally expected type is another dnum instance...
814|         if isinstance(other,type(self)):
815|             return other
816| 
817|         # Convert scalar types to string for dnum instance...
818|         if isinstance(other,int) or isinstance(other,float):
819|             return dnum(str(other))
820| 
821|         # Convert list/tuple to digits for dnum instance...
822|         if isinstance(other,list) or isinstance(other,tuple):
823|             return dnum(other)
824| 
825|         # Convert string to dnum...
826|         if isinstance(other,str):
827|             return dnum(other)
828| 
829|         raise TypeError(f'{label} with {typename(other)} not supported.')
830| 
831|     def _need_an_integer (self, other, label:str) -> int:
832|         """Ensure other is an integer value."""
833|         if isinstance(other,int):
834|             return other
835|         if isinstance(other,type(self)):
836|             return int(other)
837|         raise TypeError(f'{label} with {typename(other)} not supported.')
838| 
839|     def _combine_digits_pair (self, other, function) -> tuple:
840|         """Combine digits of self and other with a function."""
841| 
842|         whole_size = max(self.wholelen, other.wholelen)
843|         fract_size = max(self.fractlen, other.fractlen)
844|         total_size = whole_size + fract_size
845|         diff1 = whole_size - self.dp
846|         diff2 = whole_size - other.dp
847|         #print(f'size: {whole_size}.{fract_size} = {total_size} (diff: {diff1}, {diff2})', file=Log)
848| 
849|         # Result buffer...
850|         buf = [0]*total_size
851| 
852|         # Iterate over the combined pairs...
853|         for ix in range(total_size):
854|             # Get A and B digits (or zero if no digit)...
855|             a,b = 0,0
856|             if 0 <= ix-diff1 < len(self) : a = self.digits[ix-diff1]
857|             if 0 <= ix-diff2 < len(other): b = other.digits[ix-diff2]
858| 
859|             # Store results of function in buffer...
860|             buf[ix] = function(a, b)
861| 
862|         # Return tuple (digits, dp)...
863|         return (buf, whole_size)
864| 
865|     def _process_list (self, list_of_digits:list) -> tuple:
866|         """Convert a list of items to valid list of digits."""
867|         buf = []
868|         sign = +1 # ASSume
869|         dp = None
870|         for ix,value in enumerate(list_of_digits):
871|             #print(f'process-list: {ix=}, {value=}:{typename(value)}', file=Log)
872| 
873|             # Check for sign (must be first)...
874|             if value in ['+', '-']:
875|                 if 0 < ix:
876|                     raise SyntaxError(f'Plus/Minus must be first item. ({list_of_digits})')
877|                 if value=='-':
878|                     sign = -1
879|                 continue
880| 
881|             # Check for decimal point (only one allowed)...
882|             if value == '.':
883|                 if dp is not None:
884|                     raise SyntaxError(f'Only one decimal point allowed. ({list_of_digits})')
885|                 dp = len(buf)
886|                 continue
887| 
888|             # Anything else must be a valid digit...
889|             if 0 <= value < self.Base:
890|                 buf.append(value)
891|                 continue
892| 
893|             raise ValueError(f'Illegal list item: {value}')
894| 
895|         # Set dp if not already set...
896|         if dp is None:
897|             dp = len(buf)
898| 
899|         # Return tuple (digits, dp, sign)...
900|         return (buf, dp, sign)
901| 
902|     # ============ Math Methods ============
903|     def _add_ (self, other) -> tuple:
904|         """Add two dnum objects. Returns tuple (digits, dp)."""
905|         # ADD two dnum objects...
906|         buf,dp = self._combine_digits_pair(other, lambda a,b: a+b)
907| 
908|         # Ripple carry results...
909|         carry = 0
910|         for ix in reversed(range(len(buf))):
911|             carry,digit = divmod(buf[ix]+carry, self.Base)
912|             buf[ix] = digit
913| 
914|         # Final carry means an overflow digit...
915|         if 0 < carry:
916|             # Which makes the number bigger...
917|             buf.insert(0, carry)
918|             dp += 1
919| 
920|         #print(f'{buf=}, {dp=}', file=Log)
921|         # Return tuple (digits, dp)...
922|         return (buf, dp)
923| 
924|     def _sub_ (self, other) -> tuple:
925|         """Subtract two dnum objects. Returns tuple (digits, dp)."""
926|         # SUBTRACT two dnum objects...
927|         buf,dp = self._combine_digits_pair(other, lambda a,b: a-b)
928| 
929|         # Ripple borrow results...
930|         borrow = 0
931|         for ix in reversed(range(len(buf))):
932|             borrow,digit = divmod(buf[ix]+borrow, self.Base)
933|             buf[ix] = digit
934| 
935|         # Final borrow means a negative...
936|         sign = +1
937|         if borrow < 0:
938|             sign = -1
939|             digmax = self.Base - 1
940|             tmp = [digmax-digit for ix,digit in enumerate(reversed(buf))]
941|             tmp[0] += 1
942|             #print(f'{buf=}, {tmp=}', file=Log)
943|             borrow = 0
944|             for ix in range(len(tmp)):
945|                 borrow,digit = divmod(tmp[ix]+borrow, self.Base)
946|                 tmp[ix] = digit
947|             if borrow:
948|                 raise RuntimeError(f'Subtract: Unexpected carry overflow: {tmp}')
949| 
950|             # Put result in buffer...
951|             buf = list(reversed(tmp))
952| 
953|         #print(f'{buf=}, {dp=}, {sign}', file=Log)
954|         # Return tuple (digits, dp)...
955|         return (buf, dp, sign)
956| 
957|     def _multiply_ (self, other) -> list:
958|         """Multiply two dnum objects."""
959|         accum = {ix:0 for ix in range(len(self.digits)+len(other.digits))}
960| 
961|         # Generate Cartesian product of A and B (self and other)...
962|         for ax,da in enumerate(reversed(self.digits)):
963|             for bx,db in enumerate(reversed(other.digits)):
964|                 # Add product to accumulator...
965|                 accum[ax+bx] += da * db
966| 
967|         # Copy terms from accumulator to buffer with carry...
968|         buf = [0] * len(accum)
969|         carry = 0
970|         for ix in sorted(accum.keys()):
971|             carry,digit = divmod(accum[ix]+carry, self.Base)
972|             buf[ix] = digit
973| 
974|         # Should be impossible, but just in case...
975|         if 0 < carry:
976|             raise ValueError('Multiplication Overflow!')
977| 
978|         # Return list of digits...
979|         return list(reversed(buf))
980| 
981|     def _divide_ (self, other) -> tuple:
982|         """Divide two dnum objects. self÷other (self/other)"""
983|         #ATTN: Division is SLOW!
984|         #print(f'divide({self} ÷ {other})', file=Log)
985|         #print(file=Log)
986| 
987|         numer = trailingzeros(self)
988|         dp = abs(self.dp-other.dp)+1
989| 
990|         def subtract (base):
991|             '''Subtraction Loop.'''
992|             #print(f'subtract({base=})', file=Log)
993| 
994|             end = base + len(other)
995|             retv = 0
996|             #NOTE: can leading part be trimmed?
997|             while numer.compare(base, other.digits):
998|                 #print(f'{other} < {numer[:end]}', file=Log)
999| 
1000|                 for bx in reversed(range(len(other))):
1001|                     c = numer[base+bx] - other[bx]
1002|                     #print(f'N[{base+bx}] - D[{bx}] = {c}', file=Log)
1003|                     if c < 0:
1004|                         c += 10
1005|                         numer[(base+bx)-1] -= 1
1006|                     numer[base+bx] = c
1007| 
1008|                 retv += 1
1009|                 #print(file=Log)
1010| 
1011|             #print(f'subtract => {retv}; {numer}', file=Log)
1012|             return retv
1013| 
1014|         # Divide loop...
1015|         out = []
1016|         for ix in range(len(self)+self.DivPrec):
1017|             #print(f'divider[{ix}] ...', file=Log)
1018|             out.append(subtract(ix))
1019|             #print(file=Log)
1020|         #print(file=Log)
1021|         numer.ltrim()
1022| 
1023|         #print(f'divider => {out} ({dp}) R{numer}', file=Log)
1024|         # Return tuple (digits, dp, rem)...
1025|         return (out, dp, numer)
1026| 
1027| 
1028| GR = dnum('1.618,033,988,749,894,848,204,586,834,365,638,117,720,309,179,805,762,862,135,448,622')
1029| Pi = dnum('3.141,592,653,589,793,238,462,643,383,279,502,884,197,169,399,375,1')
1030| E  = dnum('2.7_1828_1828_459,045,235,360,287,471,352')
1031| C  = dnum('299,792,458')
1032| C2 = dnum('89,875,517,873,681,764')
1033| Planck = dnum('0.000000000000000000000000000000000_6_626,070,15')
1034| 
1035| 
1036| ####################################################################################################
1037| '''eof'''
1038|