2025-11-17_dual-numbers-in-python.html


001| #:name::Dual Numbers in Python
002| #:link::https://thehardcorecoder.com/2025/11/17/dual-numbers-in-python/
003| #:date::2025-11-17
004| #:code::
005| typename = lambda obj: type(obj).__name__
006| 
007| class dualnumber:
008|     Etype = 'Sorry. Unknown type: {}'
009| 
010|     def __init__ (self, real=0, dual=0):
011|         '''New Dual Number instance.'''
012|         self.real = real
013|         self.dual = dual
014| 
015|     def __repr__ (self):
016|         '''Return debug string.'''
017|         return f'<{typename(self)} @{id(self):08x}>'
018| 
019|     def __str__ (self):
020|         '''Return printable string.'''
021|         return f'({self.real:+}{self.dual:+}e)'
022| 
023|     @staticmethod
024|     def differentiate (function, x):
025|         '''Differentiate function at x and return value.'''
026|         return function(dualnumber(x,1)).dual
027| 
028|     def __add__  (self, other):
029|         '''Add with a DN or a numeric value and return new DN.'''
030| 
031|         # First see if other is another dualnumber...
032|         if isinstance(other,dualnumber):
033|             # Do the math...
034|             ta = self.real + other.real
035|             tb = self.dual + other.dual
036|             # Return a new dual number...
037|             return dualnumber(ta, tb)
038| 
039|         # Alternately, handle integers and floats...
040|         if isinstance(other,int) or isinstance(other,float):
041|             # The math here involves just the real part...
042|             ta = self.real + other
043|             tb = self.dual
044|             # Return a new dual number...
045|             return dualnumber(ta, tb)
046| 
047|         # If none of the above, that's an error...
048|         raise ValueError(dualnumber.Etype.format(typename(other)))
049| 
050|     # Addition is communitive, so Right-Add is same as Left-Add...
051|     __radd__ = __add__
052| 
053|     def __iadd__  (self, other):
054|         '''Add a DN or numeric value to self.'''
055| 
056|         # First, deal with another dualnumber...
057|         if isinstance(other,dualnumber):
058|             # Do the math to self...
059|             self.real += other.real
060|             self.dual += other.dual
061|             return self
062| 
063|         # Alternately, integers or floats...
064|         if isinstance(other,int) or isinstance(other,float):
065|             self.real += other
066|             return self
067| 
068|         # Nope...
069|         raise ValueError(dualnumber.Etype.format(typename(other)))
070| 
071|     def __sub__  (self, other):
072|         '''Subtract with a DN or a numeric value and return new DN.'''
073|         if isinstance(other,dualnumber):
074|             ta = self.real - other.real
075|             tb = self.dual - other.dual
076|             return dualnumber(ta, tb)
077|         if isinstance(other,int) or isinstance(other,float):
078|             ta = self.real - other
079|             tb = self.dual
080|             return dualnumber(ta, tb)
081|         # Nope...
082|         raise ValueError(dualnumber.Etype.format(typename(other)))
083| 
084|     def __rsub__ (self, other):
085|         '''Subtract with a DN or a numeric value and return new DN.
085|            Note that subtraction does NOT commute so we must implement rsub.
085|            Note also that other will never be a dualnumber, so we only need
085|            to handle ints and floats.'''

086|         if isinstance(other,int) or isinstance(other,float):
087|             ta = other - self.real
088|             tb = self.dual
089|             return dualnumber(ta, tb)
090|         raise ValueError(dualnumber.Etype.format(typename(other)))
091| 
092|     def __isub__  (self, other):
093|         '''Subtract a DN or numeric value from self.'''
094|         if isinstance(other,dualnumber):
095|             self.real -= other.real
096|             self.dual -= other.dual
097|             return self
098|         if isinstance(other,int) or isinstance(other,float):
099|             self.real -= other
100|             return self
101|         # Nope...
102|         raise ValueError(dualnumber.Etype.format(typename(other)))
103| 
104|     def __mul__  (self, other):
105|         '''Multiply by a DN or a numeric value and return new DN.'''
106| 
107|         # The multiplication math is a bit more involved...
108|         if isinstance(other,dualnumber):
109|             ta = self.real * other.real
110|             tb = (self.real * other.dual) + (self.dual * other.real)
111|             return dualnumber(ta, tb)
112| 
113|         # Scalar values apply to both real and dual parts...
114|         if isinstance(other,int) or isinstance(other,float):
115|             ta = self.real * other
116|             tb = self.dual * other
117|             return dualnumber(ta, tb)
118|         # Nope...
119|         raise ValueError(dualnumber.Etype.format(typename(other)))
120| 
121|     # Right-Mul same as Left-Mul...
122|     __rmul__ = __mul__
123| 
124|     def __imul__  (self, other):
125|         '''Multiply a DN or numeric value to self.'''
126|         if isinstance(other,dualnumber):
127|             ta = self.real * other.real
128|             tb = (self.real * other.dual) + (self.dual * other.real)
129|             self.real = ta
130|             self.dual = tb
131|             return self
132|         if isinstance(other,int) or isinstance(other,float):
133|             self.real *= other
134|             self.dual *= other
135|             return self
136|         # Nope...
137|         raise ValueError(dualnumber.Etype.format(typename(other)))
138| 
139|     def __pow__ (self, other, modulo=None):
140|         '''Raise a DN to a power. Exponent must be zero or positive.'''
141| 
142|         # We're only handling (positive) integer powers...
143|         if isinstance(other,int):
144|             # Not handling negative exponents, b/c no inverse...
145|             if other < 0:
146|                 raise ValueError(f'Exponent must be postive, not {other}.')
147|             # Handle exponent=0, return 1...
148|             if other == 0:
149|                 return dualnumber(1)
150|             # Create a copy...
151|             tmp = +self
152|             # Handle exponent=1, return DN...
153|             if other == 1:
154|                 return tmp
155|             # Handle higher powers...
156|             for _ in range(other-1):
157|                 tmp *= self
158|             # Return value...
159|             return tmp
160| 
161|         # Nope...
162|         raise ValueError(f'Exponent must be int, not {typename(other)}.')
163| 
164|     def __eq__ (self, other):
165|         '''See if other is equal to self.'''
166|         if other is None: return False
167| 
168|         # If other is a dualnumber, compare parts...
169|         if isinstance(other,dualnumber):
170|             if self.real != other.real: return False
171|             if self.dual != other.dual: return False
172|             return True
173| 
174|         # If other is a scalar, compare as dualnumber(x,0)...
175|         if isinstance(other,int) or isinstance(other,float):
176|             return self == dualnumber(other)
177| 
178|         # Nope...
179|         raise ValueError(dualnumber.Etype.format(typename(other)))
180| 
181|     def __ne__ (self, other):
182|         '''Not-equals is just the opposite of equals.'''
183|         return not (self == other)
184| 
185|     def __bool__ (self):
186|         '''Return True of DN is non-zero.'''
187|         return False if ((self.real==0) and (self.dual==0)) else True
188| 
189|     def __neg__ (self):
190|         '''Return a negative version of self.'''
191|         return dualnumber(-self.real, -self.dual)
192| 
193|     def __pos__ (self):
194|         '''Return a positive version of self (just duplicates).'''
195|         return dualnumber(self.real, self.dual)
196| 
197|     def __abs__ (self):
198|         '''Return the absolute value of self.'''
199|         return dualnumber(abs(self.real), abs(self.dual))
200| 
201|     def __int__ (self):
202|         '''Return real value as integer.'''
203|         return int(self.real)
204| 
205|     def __float__ (self):
206|         '''Return real value as a float.'''
207|         return float(self.real)
208| 
209| #:code::
210| from examples import dualnumber
211| 
212| if __name__ == '__main__':
213|     print()
214|     a,b = (+5, -3)
215|     c,d = (-2, +7)
216|     dn1 = dualnumber(a, b)
217|     dn2 = dualnumber(c, d)
218|     print(f'({a:+}{b:+}e) + ({c:+}{d:+}e): {dn1+dn2}')
219|     print(f'({c:+}{d:+}e) + ({a:+}{b:+}e): {dn2+dn1}')
220|     print(f'({a:+}{b:+}e) - ({c:+}{d:+}e): {dn1-dn2}')
221|     print(f'({c:+}{d:+}e) - ({a:+}{b:+}e): {dn2-dn1}')
222|     print(f'({a:+}{b:+}e) * ({c:+}{d:+}e): {dn1*dn2}')
223|     print(f'({c:+}{d:+}e) * ({a:+}{b:+}e): {dn2*dn1}')
224|     print()
225|     print(f'({a:+}{b:+}e) + 9: {dn1+9}')
226|     print(f'9 + ({a:+}{b:+}e): {9+dn1}')
227|     print(f'({a:+}{b:+}e) - 9: {dn1-9}')
228|     print(f'9 - ({a:+}{b:+}e): {9-dn1}')
229|     print(f'({a:+}{b:+}e) * 9: {dn1*9}')
230|     print(f'9 * ({a:+}{b:+}e): {9*dn1}')
231|     print()
232|     print(f'({a:+}{b:+}e) * ({a:+}{b:+}e): {dn1 * dn1}')
233|     print(f'pow(({a:+}{b:+}e),2): {pow(dn1,2)}')
234|     print()
235|     print(f'({c:+}{d:+}e) * ({c:+}{d:+}e) * ({c:+}{d:+}e): {dn2 * dn2 * dn2}')
236|     print(f'pow(({c:+}{d:+}e),3): {pow(dn2,3)}')
237|     print()
238|     print(f'({a:+}{b:+}e) == ({a:+}{b:+}e): {dn1==dn1}')
239|     print(f'({a:+}{b:+}e) == ({c:+}{d:+}e): {dn1==dn2}')
240|     print(f'({a:+}{b:+}e) != ({c:+}{d:+}e): {dn1!=dn2}')
241|     print(f'({5:+}{0:+}e) == 5: {dualnumber(5)==5}')
242|     print(f'')
243|     print()
244| 
245| #:code::
246| kwarg = lambda name,dflt,typ,args: typ(args[name]) if name in args else dflt
247| 
248| #:code::
249| from examples import kwarg
250| 
251| def make_chart (xs, ys0,ys1, **kwargs):
252|     '''Create a chart.'''
253|     from os import path
254|     from matplotlib import pyplot as plt
255|     from matplotlib.ticker import MultipleLocator
256|     from matplotlib.ticker import FormatStrFormatter
257|     from matplotlib.patches import Patch
258|     from examples import kwarg
259| 
260|     fname  = kwarg('fname', 'dualnums.png', str, kwargs)
261|     fpath  = kwarg('fpath', r'C:\Demo\HCC\Python', str, kwargs)
262|     xmin   = kwarg('xmin', -5, int, kwargs)
263|     xmax   = kwarg('xmax', +5, int, kwargs)
264|     ymin   = kwarg('ymin', -10, int, kwargs)
265|     ymax   = kwarg('ymax', +10, int, kwargs)
266|     xticks = kwarg('xticks', (1.0, 0.1), tuple, kwargs)
267|     yticks = kwarg('yticks', (1.0, 0.1), tuple, kwargs)
268|     fcolor = kwarg('fc', '#7f7f7f', str, kwargs)
269|     gcolor = kwarg('gc', '#ff0000', str, kwargs)
270|     latex = r'$\left[=\frac{d}{dx}f(x)\right]$'
271|     title  = f'f(x) & g(x) {latex} with dual numbers'
272| 
273|     # Create a new plot 6.0 inches wide and 8.0 inches tall...
274|     fig, ax = plt.subplots()
275|     fig.set_figwidth(6.0)
276|     fig.set_figheight(8.0)
277|     fig.suptitle(title, fontsize=14, fontweight='bold')
278|     fig.subplots_adjust(left=0.065, right=0.990, bottom=0.07, top=0.93)
279| 
280|     # Define X-axis properties...
281|     ax.set_xlim(xmin, xmax)
282|     ax.xaxis.set_major_locator(MultipleLocator(xticks[0]))
283|     ax.xaxis.set_minor_locator(MultipleLocator(xticks[1]))
284|     ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
285| 
286|     # Define Y-axis properties...
287|     ax.set_ylim(ymin, ymax)
288|     ax.yaxis.set_major_locator(MultipleLocator(yticks[0]))
289|     ax.yaxis.set_minor_locator(MultipleLocator(yticks[1]))
290|     ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
291| 
292|     # Define background grid properties...
293|     props = dict(axis='both', ls='-', alpha=1.0)
294|     ax.grid(which='major', color='#9f9f9f', lw=1.0, zorder=1, **props)
295|     ax.grid(which='minor', color='#bfbfbf', lw=0.6, zorder=0, **props)
296| 
297|     props = dict(axis='both', direction='out', color='#000000')
298|     ax.tick_params(which='major', **props)
299|     ax.tick_params(which='minor', **props)
300| 
301|     # Draw the X and Y axes...
302|     ax.axhline(0.0, lw=1.2, color='#000000', alpha=1.00, zorder=10)
303|     ax.axvline(0.0, lw=1.2, color='#000000', alpha=1.00, zorder=10)
304| 
305|     # Plot f(x) and g(x)...
306|     ax.plot(xs,ys0, label='f(x)', c=fcolor, lw=2.5, alpha=0.8, zorder=11)
307|     ax.plot(xs,ys1, label='g(x)', c=gcolor, lw=2.5, alpha=0.8, zorder=12)
308| 
309|     # Define legend...
310|     patchs = [
311|         Patch(facecolor=fcolor, edgecolor='#000000', lw=0.75),
312|         Patch(facecolor=gcolor, edgecolor='#000000', lw=0.75),
313|     ]
314|     labels = ['f(x)', 'g(x)']
315|     fig.legend(
316|         patchs,
317|         labels,
318|         loc='lower right',
319|         ncols=2,
320|         fontsize=10,
321|         bbox_to_anchor=(0.99,0.00)
322|     )
323| 
324|     # Save the chart as an image file...
325|     filename = path.join(fpath,fname) if fpath else fname
326|     fig.savefig(filename)
327|     print(f'wrote: {filename}')
328|     print()
329| 
330| #:code::
331| from examples import make_chart
332| 
333| if __name__ == '__main__':
334|     print()
335|     fname = 'dualnums-test.png'
336| 
337|     # Make some data...
338|     nsteps = 200
339|     stepsize = 6.0 / 200
340| 
341|     # The Xs from from -3.0 to +3.0 (200 steps)...
342|     xs = [-3.0+(ix*stepsize) for ix in range(nsteps)]
343| 
344|     # f(x) = x^3
345|     ys1 = [pow(x,3) for x in xs]
346|     # f'(x) = 3x^2
347|     ys2 = [3*pow(x,2) for x in xs]
348| 
349|     # Make a chart of the data...
350|     props = dict(xmin=-3,xmax=+3, ymin=-8,ymax=+8, fname=fname)
351|     make_chart(xs, ys1,ys2, **props)
352|     print()
353| 
354| #:code::
355| from sys import argv, exc_info
356| from traceback import extract_tb
357| from examples import kwarg, dualnumber, make_chart
358| 
359| def main (**kwargs):
360|     '''Dual number demo.'''
361|     fname = kwarg('fname', 'dualnums.png', str, kwargs)
362|     fpath = kwarg('fpath', r'C:\Demo\HCC\Python', str, kwargs)
363|     poly  = kwarg('poly', '2,-7,5', str, kwargs)
364|     xmin  = kwarg('xmin', -5.0, float, kwargs)
365|     xmax  = kwarg('xmax', +5.0, float, kwargs)
366|     ymin  = kwarg('ymin', -5.0, float, kwargs)
367|     ymax  = kwarg('ymax', +5.0, float, kwargs)
368|     xtix  = kwarg('xtix', '1.0, 0.1', str, kwargs)
369|     ytix  = kwarg('ytix', '1.0, 0.1', str, kwargs)
370|     divs  = kwarg('divs', 500, int, kwargs)
371| 
372|     coefficients = [float(n.strip()) for n in reversed(poly.split(','))]
373| 
374|     def f (x):
375|         accum = float()
376|         for expon,coe in enumerate(coefficients):
377|             accum += (coe * pow(x,expon))
378|         return accum
379| 
380|     # Generate X-axis...
381|     stepsize = (xmax-xmin)/divs
382|     xs = [xmin+(ix*stepsize) for ix in range(divs)]
383| 
384|     # Generate data: f(x) and g(x)...
385|     fys = [f(x) for x in xs]
386|     gys = [dualnumber.differentiate(f,x) for x in xs]
387| 
388|     props = {
389|         'fname': fname, 'fpath':fpath,
390|         'xmin': xmin, 'xmax': xmax,
391|         'ymin': ymin, 'ymax': ymax,
392|         'xticks': tuple(float(n.strip()) for n in xtix.split(',',1)),
393|         'yticks': tuple(float(n.strip()) for n in ytix.split(',',1)),
394|     }
395|     make_chart(xs, fys,gys, **props)
396| 
397| if __name__ == '__main__':
398|     print(argv[0])
399|     print()
400| 
401|     # Convert commandline args to keyword args...
402|     kwargs = {}
403|     for arg in argv[1:]:
404|         nam,val = arg.split('=',1)
405|         kwargs[nam] = val
406| 
407|     # Call main from inside a try/except...
408|     try:
409|         main(**kwargs)
410| 
411|     except:
412|         # Print exception data in a nice, clear way...
413|         etype, evalue, tb = exc_info()
414|         ts = extract_tb(tb)
415|         print()
416|         print(f'{etype.__name__}: {evalue!s}')
417|         print()
418|         for t in ts[-5:]:
419|             print(f'[{t[1]}] {t[2]} ({t[0]})')
420|             print(f' {t[3]}')
421|             print()
422|         print()
423|     print()
424| 
425| #:end:code::
426|