dualnumber.html
001| '''Dual Numbers.
001|
001| Rule #1: e is not zero
001| Rule #2: e*e = 0
001|
001| E.G. #1
001| f(x) = 2x^2 - 7x + 5
001| g(x) = 4x - 7
001|
001| f(x+e) = 2(x+e)^2 - 7(x+e)^1 + 5
001| = 2(x+e)(x+e) - 7(x+e) + 5
001| = 2(x^2 + 2xe + e^2) - 7x - 7e + 5
001| = (2x^2 - 7x + 5) + (4x - 7)e
001|
001| E.G. #2
001| f(x) = 0.5x^3 + 1.5x^2 - 5.5x - 2.7
001| g(x) = 1.5x^2 + 3.0x - 5.5
001|
001| f(x+e) = 0.5(x+e)^3 + 1.5(x+e)^2 - 5.5(x+e) - 2.7
001| = 0.5(x+e)(x+e)(x+e) + 1.5(x+e)(x+e) - 5.5(x+e) - 2.7
001| = 0.5(x+e)(x^2 + 2xe + e^2) + 1.5(x^2 + 2xe + e^2) - 5.5x - 5.5e - 2.7
001| = 0.5(x^3 + 3x^2e) + 1.5(x^2 + 2xe) - 5.5x - 5.5e - 2.7
001| = (0.5x^3 + 1.5x^2 - 5.5x - 2.7) + (1.5x^2 + 3.0x - 5.5)e
001|
001| Commandline Arguments:
001| poly -str/csv: polynomial coefficients (default: "0.5, 0, 0")
001| divs -int: divisions to X-axis (default: 500)
001| xmin -float: X-axis minimum (default: -5.0)
001| xmax -float; X-axis maximum (default: +5.0)
001| ymin -float: Y-axis minimum (default: -5.0)
001| ymax -float: Y-axis maximum (default: +5.0)
001| xtix -str/csv: X-axis tick spacing (default: "1.0, 0.1")
001| ytix -str/csv: Y-axis tick spacing (default: "1.0, 0.1")
001| fname -str: chart filename (default: "dualnums.png")
001| fpath -str: chart filepath (default: BasePath)
001|
001| '''
002|
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from matplotlib import pyplot as plt
007| from matplotlib.ticker import MultipleLocator
008| from matplotlib.ticker import FormatStrFormatter
009| from matplotlib.patches import Patch
010| from goodies import KWARG, typename, divisions
011|
012| BasePath = r'C:\CJS\prj\Python\blog\hcc\source'
013|
014| ARGS = {
015|
016|
017| 'poly': '0.1, 0.33, -0.75, -2.7, -3.1415',
018| 'divs': '500',
019|
020| 'xmin': '-6.0', 'xmax': '+4.0',
021| 'xtix': '1.0, 0.5',
022|
023| 'ymin': '-10.0', 'ymax': '+5.0',
024| 'ytix': '1.0, 0.5',
025|
026|
027|
028| }
029|
030|
031| class dualnumber:
032| Etype = 'Sorry. Unknown type: {}'
033|
034| def __init__ (self, real=0, dual=0):
035| '''New Dual Number instance.'''
036| self.real = real
037| self.dual = dual
038|
039|
040| __hash__ = None
041|
042| def __add__ (self, other):
043| '''Add with a DN or a numeric value and return new DN.'''
044| if isinstance(other,dualnumber):
045| ta = self.real + other.real
046| tb = self.dual + other.dual
047| return dualnumber(ta, tb)
048| if isinstance(other,int) or isinstance(other,float):
049| ta = self.real + other
050| tb = self.dual
051| return dualnumber(ta, tb)
052| raise ValueError(dualnumber.Etype.format(typename(other)))
053|
054|
055| __radd__ = __add__
056|
057| def __iadd__ (self, other):
058| '''Add a DN or numeric value to self.'''
059| if isinstance(other,dualnumber):
060| self.real += other.real
061| self.dual += other.dual
062| return self
063| if isinstance(other,int) or isinstance(other,float):
064| self.real += other
065| return self
066| raise ValueError(dualnumber.Etype.format(typename(other)))
067|
068| def __sub__ (self, other):
069| '''Subtract with a DN or a numeric value and return new DN.'''
070| if isinstance(other,dualnumber):
071| ta = self.real - other.real
072| tb = self.dual - other.dual
073| return dualnumber(ta, tb)
074| if isinstance(other,int) or isinstance(other,float):
075| ta = self.real - other
076| tb = self.dual
077| return dualnumber(ta, tb)
078| raise ValueError(dualnumber.Etype.format(typename(other)))
079|
080| __rsub__ = __sub__
081|
082| def __isub__ (self, other):
083| '''Subtract a DN or numeric value from self.'''
084| if isinstance(other,dualnumber):
085| self.real -= other.real
086| self.dual -= other.dual
087| return self
088| if isinstance(other,int) or isinstance(other,float):
089| self.real -= other
090| return self
091| raise ValueError(dualnumber.Etype.format(typename(other)))
092|
093| def __mul__ (self, other):
094| '''Multiply by a DN or a numeric value and return new DN.'''
095| if isinstance(other,dualnumber):
096| ta = self.real * other.real
097| tb = (self.real * other.dual) + (self.dual * other.real)
098| return dualnumber(ta, tb)
099| if isinstance(other,int) or isinstance(other,float):
100| ta = self.real * other
101| tb = self.dual * other
102| return dualnumber(ta, tb)
103| raise ValueError(dualnumber.Etype.format(typename(other)))
104|
105|
106| __rmul__ = __mul__
107|
108| def __imul__ (self, other):
109| '''Multiply a DN or numeric value to self.'''
110| if isinstance(other,dualnumber):
111| ta = self.real * other.real
112| tb = (self.real * other.dual) + (self.dual * other.real)
113| self.real = ta
114| self.dual = tb
115| return self
116| if isinstance(other,int) or isinstance(other,float):
117| self.real *= other
118| self.dual *= other
119| return self
120| raise ValueError(dualnumber.Etype.format(typename(other)))
121|
122| def __pow__ (self, other, modulo=None):
123| '''Raise a DN to a power. Exponent must be zero or positive.'''
124| if isinstance(other,int):
125|
126| if other < 0:
127| raise ValueError(f'Exponent must be postive, not {other}.')
128|
129| if other == 0:
130| return dualnumber(1)
131| tmp = +self
132|
133| if other == 1:
134| return tmp
135| for _ in range(other-1):
136| tmp *= self
137| return tmp
138| raise ValueError(f'Exponent must be int, not {typename(other)}.')
139|
140| def __neg__ (self):
141| '''Return a negative version of self.'''
142| return dualnumber(-self.real, -self.dual)
143|
144| def __pos__ (self):
145| '''Return a positive version of self (just duplicates).'''
146| return dualnumber(self.real, self.dual)
147|
148| def __abs__ (self):
149| '''Return the absolute value of self.'''
150| return dualnumber(abs(self.real), abs(self.dual))
151|
152| def __bool__ (self):
153| '''Return True of DN is non-zero.'''
154| return False if ((self.real==0) and (self.dual==0)) else True
155|
156| def __int__ (self):
157| '''Return real value as integer.'''
158| return int(self.real)
159|
160| def __float__ (self):
161| '''Return real value as a float.'''
162| return float(self.real)
163|
164| def __repr__ (self):
165| '''Return debug string.'''
166| return f'<{typename(self)} @{id(self):08x}>'
167|
168| def __str__ (self):
169| '''Return printable string.'''
170| return f'({self.real}, {self.dual}e)'
171|
172| @staticmethod
173| def differentiate (function, x):
174| '''Differentiate function at x and return value.'''
175| return function(dualnumber(x,1)).dual
176|
177|
178|
179|
180| def make_chart (xs, ys0,ys1, **kwargs):
181| '''Create a chart.'''
182| fname = KWARG('fname', 'dualnums.png', str, kwargs)
183| fpath = KWARG('fpath', BasePath, str, kwargs)
184| xmin = KWARG('xmin', -5, int, kwargs)
185| xmax = KWARG('xmax', +5, int, kwargs)
186| ymin = KWARG('ymin', -10, int, kwargs)
187| ymax = KWARG('ymax', +10, int, kwargs)
188| xticks = KWARG('xticks', (1.0, 0.1), tuple, kwargs)
189| yticks = KWARG('yticks', (1.0, 0.1), tuple, kwargs)
190| fcolor = KWARG('fc', '#7f7f7f', str, kwargs)
191| gcolor = KWARG('gc', '#ff0000', str, kwargs)
192|
193|
194| fig, ax = plt.subplots()
195| fig.set_figwidth(6.0)
196| fig.set_figheight(8.0)
197| fig.suptitle(r'f(x) and g(x) $\left[=\frac{d}{dx}f(x)\right]$ using "Dual Numbers"', fontsize=14, fontweight='bold')
198| fig.subplots_adjust(left=0.065, right=0.990, bottom=0.07, top=0.93)
199|
200|
201|
202| ax.set_xlim(xmin, xmax)
203| ax.xaxis.set_major_locator(MultipleLocator(xticks[0]))
204| ax.xaxis.set_minor_locator(MultipleLocator(xticks[1]))
205| ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
206|
207|
208|
209|
210|
211|
212|
213| ax.set_ylim(ymin, ymax)
214| ax.yaxis.set_major_locator(MultipleLocator(yticks[0]))
215| ax.yaxis.set_minor_locator(MultipleLocator(yticks[1]))
216| ax.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
217|
218|
219| ax.grid(which='major', axis='both', color='#9f9f9f', lw=1.0,ls='-',zorder=1, alpha=1.0)
220| ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
221| ax.tick_params(which='major', axis='both', direction='out', color='#000000')
222| ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
223|
224|
225| ax.axhline(0.0, lw=1.2, color='#000000', alpha=1.00, zorder=10)
226| ax.axvline(0.0, lw=1.2, color='#000000', alpha=1.00, zorder=10)
227|
228|
229| ax.plot(xs,ys0, label='f(x)', c=fcolor, lw=2.5, alpha=0.8, zorder=11)
230| ax.plot(xs,ys1, label='g(x)', c=gcolor, lw=2.5, alpha=0.8, zorder=12)
231|
232|
233| patchs = [
234| Patch(facecolor=fcolor, edgecolor='#000000', lw=0.75),
235| Patch(facecolor=gcolor, edgecolor='#000000', lw=0.75),
236| ]
237| labels = ['f(x)', 'g(x)']
238| fig.legend(patchs, labels, loc='lower right', ncols=2, fontsize=10, bbox_to_anchor=(0.99,0.00))
239|
240|
241| filename = path.join(fpath,fname) if fpath else fname
242| fig.savefig(filename)
243| print(f'wrote: {filename}')
244| print()
245|
246|
247|
248| def main (**kwargs):
249| '''Dual number demo.'''
250| fname = KWARG('fname', 'dualnums.png', str, kwargs)
251| fpath = KWARG('fpath', BasePath, str, kwargs)
252| poly = KWARG('poly', '0.5, 0, 0', str, kwargs)
253| xmin = KWARG('xmin', -5.0, float, kwargs)
254| xmax = KWARG('xmax', +5.0, float, kwargs)
255| ymin = KWARG('ymin', -5.0, float, kwargs)
256| ymax = KWARG('ymax', +5.0, float, kwargs)
257| xtix = KWARG('xtix', '1.0, 0.1', str, kwargs)
258| ytix = KWARG('ytix', '1.0, 0.1', str, kwargs)
259| divs = KWARG('divs', 500, int, kwargs)
260|
261| coefficients = [float(n.strip()) for n in reversed(poly.split(','))]
262|
263| def f (x):
264|
265|
266| accum = float()
267| for expon,coe in enumerate(coefficients):
268| accum += (coe * pow(x,expon))
269| return accum
270|
271|
272| xs = list(divisions(xmin, xmax, divs))
273|
274|
275| fys = [f(x) for x in xs]
276| gys = [dualnumber.differentiate(f,x) for x in xs]
277|
278| props = {
279| 'fname': fname, 'fpath':fpath,
280| 'xmin': xmin, 'xmax': xmax,
281| 'ymin': ymin, 'ymax': ymax,
282| 'xticks': tuple(float(n.strip()) for n in xtix.split(',',1)),
283| 'yticks': tuple(float(n.strip()) for n in ytix.split(',',1)),
284| }
285| make_chart(xs,fys,gys, **props)
286|
287| return (f, xs, fys,gys)
288|
289| if __name__ == '__main__':
290| print(argv[0])
291| print()
292|
293| kwargs = ARGS
294| for arg in argv[1:]:
295| nam,val = arg.split('=',1)
296| kwargs[nam] = val
297|
298| try:
299| ftn,xs,fs,gs = main(**kwargs)
300| except:
301|
302| etype, evalue, tb = exc_info()
303| ts = extract_tb(tb)
304| print()
305| print(f'{etype.__name__}: {evalue!s}')
306| print()
307| for t in ts[-5:]:
308| print(f'[{t[1]}] {t[2]} ({t[0]})')
309| print(f' {t[3]}')
310| print()
311| print()
312| print()
313|
314| '''eof'''
315|