calculate_e.html


001| '''Calculate the value of the special number e.
001| 
001| Functions:
001|     calc_e_real_n           (n, log_steps)  - calculate e using (1+1/n)^n
001|     calc_e_imag_n           (n, log_steps)  - calculate e using (1+i/n)^n
001|     calc_e_real_pow         (p)             - s/a calc_e_real_n(10^p)
001|     calc_e_imag_pow         (p)             - s/a calc_e_imag_n(10^p)
001|     pascal_triangle_row     (chain)         - generate one row of PT
001|     pascal_triangle         (#rows)         - generate PT data structure
001|     wheel                   (steps,cycles)  - exp cycle generator
001|     compare_exp_and_approx  (m)             - compare exp() with approximation
001|     converge_exp_and_approx (m,z)           - show approximation's convergence
001| 
001| Classes:
001|     calc_e (levels)                         - all-in-one Pascal's Triangle/real-e/complex-e
001| 
001| Commands:
001|     real        do_calc_e_real              - converge on the (real) value of e up to power {n}: (1+1/n)^n
001|     imag        do_calc_e_imag              - converge on the (imag) value of e up to power {n}: (1+i/n)^n
001| 
001|     c:real      do_calc_e_real_chart        - (not implemented; doesn't do anything)
001|     c:imag      do_calc_e_imag_chart        - chart points converging on (1+i/n)^n
001| 
001|     demo:real   do_calc_e_real_demo         - demonstrate converging at different iterations
001|     demo:imag   do_calc_e_imag_demo         - demonstrate converging at different iterations
001| 
001|     tri.float   do_calc_e_triangle_float    - calculate terms using {which} level of Pascal's triangle
001|     tri.frac    do_calc_e_triangle_fraction - calculate terms using {which} level of Pascal's triangle
001|     tri.cmplx   do_calc_e_triangle_complex  - calculate terms using {which} level of Pascal's triangle
001|     tri.multi   do_calc_e_tri_cmplx_multi   - iterates tri.cmplx
001| 
001|     $tri        do_list_pascals_triangle    - list Pascal's triangle to {n} many levels
001|     $loop       do_terms_loop_demo          - iteration vs recursion
001|     $exp        do_exp_tests                - convergence of exp() implementation
001|     demo        do_exp_demo                 - demonstrate exp() function
001|     test        do_test                     - sandbox
001| 
001| '''

002| ####################################################################################################
003| from sys import argv, exc_info
004| from traceback import extract_tb
005| from os import path
006| from time import process_time_ns
007| from math import exp as r_exp, e,pi,tau, degrees,atan2, factorial
008| from cmath import exp as c_exp
009| from fractions import Fraction
010| from logger import logger,info,debug,trace, LogFilenameTimestamp
011| from files import linefile
012| from mlchart import mlchart
013| from goodies import KWARG, zstrFactory, estrFactory
014| ####################################################################################################
015| BasePath = r'C:\CJS\prj\Python\app\maths'
016| ImgsPath = path.join(BasePath, 'img')
017| Log = logger('calc_e')
018| 
019| CMND = ''
020| ARGS = {
021|     #'n': '5',
022|     #'which': '-1',
023|     #'p': '9',
024|     #'fname': 'calc_e.out',
025|     #'fpath': BasePath,
026| }
027| 
028| one = complex(1, 0)
029| eye = complex(0, 1)
030| i2pi = eye*complex(tau,0)
031| exp_eye = c_exp(eye)
032| 
033| zstr = zstrFactory(15)
034| estr = estrFactory(15)
035| 
036| ##================================================================================================##
037| ## PASCAL'S TRIANGLE
038| ##================================================================================================##
039| def pascal_triangle_row (chain=None):
040|     """Generate the next row of Pascal's Triangle given the current row. Returns (len,row,sum,curr-row) tuple."""
041|     seed = [1] if chain is None else chain
042|     Log.trace("Pascal's_Triangle_Row(%d)" % len(seed))
043|     buff = [seed[0]]
044|     for ix in range(1,len(seed)):
045|         buff.append(seed[ix-1] + seed[ix])
046|     buff.append(seed[-1])
047|     return (len(buff), buff, sum(buff), seed)
048| 
049| ##================================================================================================##
050| def pascal_triangle (nbr_of_rows=6):
051|     """Generate Pascal's Triangle. Returns list of (row, sum) tuples."""
052|     Log.debug("Pascal's_Triangle(%d)" % nbr_of_rows)
053|     t = [1, [1], 1, None]
054|     buff = []
055|     buff.append((t[1],t[2]))
056|     for ix in range(nbr_of_rows):
057|         t = pascal_triangle_row(t[1])
058|         buff.append((t[1],t[2]))
059|     return buff
060| 
061| 
062| ##================================================================================================##
063| ## IMPLEMENT EXP()
064| ##================================================================================================##
065| EE = lambda m:lambda x:sum([(pow(x,n)/factorial(n)) for n in range(m)])
066| 
067| ##================================================================================================##
068| def wheel (steps=36, cycles=1):
069|     """Use complex version of exp() to generate cos/sin values."""
070|     Log.trace('Wheel:')
071|     for ix in range(1+int(cycles*steps)):
072|         x = float(ix)/float(steps)
073|         c = c_exp(i2pi*x)
074|         Log.trace('%4d: %10.6f -> %+10.8f, %+10.8f' % (ix,x,c.real,c.imag))
075|     Log.trace()
076| 
077| ##================================================================================================##
078| def compare_exp_and_approx (m=10):
079|     """Compare standard exp() with an approximation with limited steps."""
080|     Log.trace('Compare:')
081|     my_exp = EE(171) # max=171
082|     eg0 = [r_exp(n) for n in range(0,m)]
083|     eg1 = [my_exp(n) for n in range(0,m)]
084|     dif = [(a,a-b) for a,b in zip(eg0,eg1)]
085|     for v,d in dif:
086|         Log.trace('%22.16f: %+22.16f' % (v,d))
087|     Log.trace()
088| 
089| ##================================================================================================##
090| def converge_exp_and_approx (m=10, z=complex(0.5,0)):
091|     """Show convergence of approximation with N steps."""
092|     Log.trace('Converge:')
093|     for n in range(1, m+1):
094|         my_exp = EE(n)
095|         c = my_exp(i2pi*z)
096|         Log.trace('%2d: (%+21.16f, %+21.16fi)' % (n, c.real,c.imag))
097|     Log.trace()
098| 
099| 
100| ##================================================================================================##
101| ## CALCULATE E - SHIFT REGISTER METHOD
102| ##------------------------------------------------------------------------------------------------##
103| coef2str = lambda c:('%+d%s'%(c[0],'*i' if c[1] else ''))
104| term2str = lambda t:('%+.9e = %s' % (float(t),t))
105| 
106| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
107| class calc_e:
108|     """\
108| Class for approximating the number e. Builds a version of Pascal's Triangle
108| that allows for imaginary values. The rows of the Triangle have the values
108| used as coefficients for the approximation series of the same length.
108| 
108| Table nodes are modeled as tuples: (num-val, i-flag). This allows them to
108| be treated as potentially imaginary values (if the i-flag is set. Values
108| can also be negative (which isn't normally seen in Pascal's Triangle.
108| """

109|     def __init__ (self, levels=9):
110|         '''New e approximation calculator instance.'''
111|         self.table = [[(1,0)]]
112| 
113|         def shift (term):
114|             # Return a shifted version of term...
115|             if term[1]:
116|                 # Imaginary term: i^2 = -1...
117|                 return (-term[0], 0)
118|             # Real term: becomes imaginary...
119|             return (term[0], 1)
120| 
121|         def adder (term_a, term_b):
122|             # Add the numeric terms...
123|             c0 = term_a[0] + term_b[0]
124|             # Set i_flag if set in A or B...
125|             c1 = 1 if (term_a[1] or term_b[1]) else 0
126|             return (c0, c1)
127| 
128|         def next_row (row):
129|             ts0  = row + [(0,0)]
130|             ts1 = [(0,0)] + [shift(t) for t in row]
131|             # Return ts0+ts1...
132|             return [adder(a,b) for a,b in zip(ts0,ts1)]
133| 
134|         # Generate table of rows of coefficients...
135|         for ix in range(levels):
136|             row = next_row(self.table[-1])
137|             self.table.append(row)
138| 
139|     def __len__ (self): return len(self.table)
140|     def __getitem__ (self, which): return self.table[which]
141|     def __setitem__ (self, which, val): raise NotImplementedError('Not allowed to change rows!')
142|     def __delitem__ (self, which, val): raise NotImplementedError('Not allowed to delete rows!')
143| 
144|     def as_numbers (self, which_row=-1):
145|         '''Return a table row as a list of plain (natural) numbers.'''
146|         return [abs(c[0]) for c in self[which_row]]
147| 
148|     def as_integers (self, which_row=-1):
149|         '''Return a table row as a list of signed (integer) numbers.'''
150|         return [c[0] for c in self[which_row]]
151| 
152|     def as_tuples (self, which_row=-1):
153|         '''Return a table row as a list of tuples.'''
154|         coeffs = self[which_row]
155|         denom = len(coeffs) - 1
156|         terms = []
157|         for ix,c in enumerate(coeffs):
158|             term = (c[0], pow(denom,ix))
159|             terms.append(term)
160|         return terms
161| 
162|     def as_terms_real (self, which_row=-1):
163|         '''Return a table row as a list of real terms (Fractions).'''
164|         coeffs = self[which_row]
165|         denom = len(coeffs) - 1
166|         terms = []
167|         for ix,c in enumerate(coeffs):
168|             term = Fraction(abs(c[0]), pow(denom,ix))
169|             terms.append(term)
170|         real_value = float(sum(terms))
171|         return (real_value, terms)
172| 
173|     def as_terms_imag (self, which_row=-1):
174|         '''Return a table row as a list of real and imaginary terms (Fractions).'''
175|         coeffs = self[which_row]
176|         denom = len(coeffs) - 1
177|         real_terms = []
178|         imag_terms = []
179|         for ix,c in enumerate(coeffs):
180|             term = Fraction(c[0], pow(denom,ix))
181|             if c[1]:
182|                 imag_terms.append(term)
183|             else:
184|                 real_terms.append(term)
185|         real_value = float(sum(real_terms))
186|         imag_value = float(sum(imag_terms))
187|         z = complex(real_value, imag_value)
188|         return (z, real_terms, imag_terms)
189| 
190|     def prn_table (self):
191|         '''Print the entire table of coefficients.'''
192|         for row in self.table:
193|             print([coef2str(c) for c in row])
194|         print()
195| 
196|     def prn_numbers (self, which_row=-1):
197|         '''Print a row of the table as a list of plain (natural) numbers.'''
198|         nmbrs = self.as_numbers(which_row)
199|         print(','.join([str(n) for n in nmbrs]))
200| 
201|     def prn_integers (self, which_row=-1):
202|         '''Print a row of the table as a list of signed (integer) numbers.'''
203|         nmbrs = self.as_integers(which_row)
204|         print(','.join([str(n) for n in nmbrs]))
205| 
206|     def prn_tuples (self, which_row=-1):
207|         '''Print a row of the table as a list of tuples.'''
208|         ts = self.as_tuples(which_row)
209|         for t in ts:
210|             print(t)
211|         print()
212| 
213|     def prn_terms_real (self, which_row=-1):
214|         '''Print a row of the table as a list of real terms.'''
215|         val,terms = self.as_terms_real(which_row)
216|         for t in terms:
217|             print(term2str(t))
218|         print('\n%.12f\n' % val)
219| 
220|     def prn_terms_imag (self, which_row=-1):
221|         '''Print a row of the table as a list of real/imaginary terms.'''
222|         val,rts,its = self.as_terms_imag(which_row)
223|         xr,xi = list(rts), list(its)
224|         terms = []
225|         while 0 < (len(xr)+len(xi)):
226|             if 0 < len(xr): terms.append(xr.pop(0))
227|             if 0 < len(xi): terms.append(xi.pop(0))
228|         for term in terms:
229|             print(term2str(term))
230|         print()
231|         print(zstr(val))
232|         print()
233| 
234|     def __str__ (self):
235|         '''String version for friendliness.'''
236|         return 'calc-e[%d]' % len(self)
237| 
238|     def __repr__ (self):
239|         '''JSON-like version for persistance.'''
240|         return '{calc_e:{levels:%d}}' % len(self)
241| 
242| 
243| ##================================================================================================##
244| ## CALCULATE E
245| ##================================================================================================##
246| def calc_e_real_n (n, capture_steps=0, capture_max_power=4):
247|     """\
247| Calculate the (real) value of e by iterating (1+1/n)^n.
247| 
247| Takes N, the number of times to iterate (i.e. the power).
247| 
247| Returns the result OR a list of results from start to final, depending
247| on whether the capture_steps flag is set. Note that this flag is forced
247| off if {10000 < steps} (by default; adjust with capture_max_power).
247| """

248|     Log.debug('calc_e_real_n(%d)' % n)
249|     if pow(10,capture_max_power) < n: capture_steps=0
250|     tot = 1.0
251|     data = [tot]
252|     # Calculate...
253|     t0 = process_time_ns()
254|     for ix in range(n):
255|         tot *= (1.0 + (1.0/n))
256|         if capture_steps: data.append(tot)
257|     t1 = process_time_ns()
258|     # Report...
259|     Log.info('RESULT: e=%.12f diff=%.9e n=%d' % (tot,e-tot,n))
260|     Log.debug('> %.9f secs' % ((t1-t0)/1000000000))
261|     Log.info()
262|     print('e=%.12f (approx) [levels: %d]' % (tot,n))
263|     print()
264|     return data if capture_steps else tot
265| 
266| ##================================================================================================##
267| def calc_e_imag_n (n, capture_steps=0, capture_max_power=4):
268|     """\
268| Calculate the complex value of e using (1+i/n)^n.
268| 
268| Takes N, the number of times to iterate (i.e. the power).
268| 
268| Returns the result OR a list of results from start to final, depending
268| on whether the capture_steps flag is set. Note that this flag is forced
268| off if {10000 < steps} (by default; adjust with capture_max_power).
268| """

269|     Log.debug('calc_e_imag_n(%d)' % n)
270|     if pow(10,capture_max_power) < n: capture_steps=0
271|     tot = complex(1,0)
272|     data = [tot]
273|     # Calculate...
274|     t0 = process_time_ns()
275|     for ix in range(n):
276|         tot *= complex(1.0, 1.0/n)
277|         if capture_steps: data.append(tot)
278|     t1 = process_time_ns()
279|     # Report...
280|     Log.info('RESULT: e=%s diff=%s n=%d' % (zstr(tot),estr(exp_eye-tot),n))
281|     Log.debug('> %.9f secs' % ((t1-t0)/1000000000))
282|     Log.debug()
283|     print('e=%s (approx) [levels: %d]' % (zstr(tot),n))
284|     print()
285|     return data if capture_steps else tot
286| 
287| ##================================================================================================##
288| def calc_e_real_pow (p=2):
289|     """Call calc_e_real_n using a power of ten."""
290|     Log.debug('calc_e_real_pow(%d)' % p)
291|     return calc_e_real_n(pow(10,p), capture_steps=0)
292| ##================================================================================================##
293| def calc_e_imag_pow (p=3):
294|     """Call calc_e_imag_n using a power of ten."""
295|     Log.debug('calc_e_imag_pow(%d)' % p)
296|     return calc_e_imag_n(pow(10,p), capture_steps=0)
297| 
298| 
299| ##================================================================================================##
300| def do_calc_e_real_chart (**kwargs):
301|     """CMND: Generate a chart of steps to real e."""
302|     fpath = KWARG('fpath', ImgsPath, str, kwargs)
303|     fname = KWARG('fname', 'calc_e_real.png', str, kwargs)
304|     n = KWARG('n', 6, int, kwargs)
305|     Log.info('calculate-e-real-chart:: %s' % str(list(kwargs.keys())))
306|     Log.debug('fpath="%s"' % fpath)
307|     Log.debug('fname="%s"' % fname)
308|     Log.debug('n=%d' % n)
309|     Log.info()
310|     # Done...
311|     Log.info()
312|     return 'Done'
313| ##================================================================================================##
314| def do_calc_e_imag_chart (**kwargs):
315|     """CMND: Generate a chart of steps to complex e."""
316|     fpath = KWARG('fpath', ImgsPath, str, kwargs)
317|     fname = KWARG('fname', 'calc_e_imag.png', str, kwargs)
318|     n = KWARG('n', 6, int, kwargs)
319|     Log.info('calculate-e-imag-chart:: %s' % str(list(kwargs.keys())))
320|     Log.debug('fpath="%s"' % fpath)
321|     Log.debug('fname="%s"' % fname)
322|     Log.debug('n=%d' % n)
323|     Log.info()
324| 
325|     class cplane_chart (mlchart):
326|         def __init__ (self, data=None, **kwargs):
327|             super().__init__((6.0, 6.0), **kwargs)
328|             self.data = [(z.real, z.imag) for z in data]
329|             self.title = 'The Complex Plane'
330|             self.x_title = 'X-Axis'
331|             self.y_title = 'Yi-Axis'
332|             self.x_limit = (-0.1, +1.1)
333|             self.y_limit = (-0.1, +1.1)
334|             self.x_grids = (1.0, 0.10)
335|             self.y_grids = (1.0, 0.10)
336|             self.x_tickf = '%+.2f'
337|             self.y_tickf = '%+.2f'
338|             self.x_tickr = True         # rotate X axis
339|             self.title_kw['fontsize'] = 24
340|             self.x_title_kw['fontsize'] = 16
341|             self.y_title_kw['fontsize'] = 16
342|             self.fpath = fpath
343|             self.fname = fname
344|             self.margins = dict(left=0.15, right=0.98, bottom=0.15, top=0.90)
345| 
346|         def plotter (self):
347|             """Plot something!"""
348|             self.ax.axvline(0, self.y_limit[0], self.y_limit[1], color='#3f3f3f', lw=2.0, zorder=9)
349|             self.ax.axhline(0, self.x_limit[0], self.x_limit[1], color='#3f3f3f', lw=2.0, zorder=9)
350|             if self.data is None:
351|                 return
352|             xs = [t[0] for t in self.data]
353|             ys = [t[1] for t in self.data]
354|             self.ax.plot(xs,ys, c='#ff0000', lw=1.2, marker='o', ms=3, alpha=0.75, zorder=11)
355| 
356|     # Generate steps...
357|     steps = calc_e_imag_n(n, capture_steps=1)
358|     Log.info(steps)
359|     # Make the chart...
360|     cht = cplane_chart(steps)
361|     cht.make()
362|     # Done...
363|     Log.info()
364|     return 'Done'
365| 
366| ##================================================================================================##
367| def do_calc_e_real (**kwargs):
368|     """\
368| CMND: Calculate specified different resolutions of (real) e using (1+1/n)^n.
368| 
368| Takes N, the number of times to iterate (i.e. the power).
368| 
368| Converging on: exp(1)=2.718281828459
368| """

369|     n = KWARG('n', 20, int, kwargs)
370|     Log.info('calculate-e-real:: %s' % str(list(kwargs.keys())))
371|     Log.debug('n=%d' % n)
372|     Log.info()
373| 
374|     retv = calc_e_real_n(n, capture_steps=1)
375|     Log.info('exp(1)=%.12f' % r_exp(1))
376|     Log.info('e=%.12f' % e)
377|     Log.info()
378|     if isinstance(retv,list):
379|         print('START: %s' % retv[0])
380|         Log.debug('START: %s' % retv[0])
381|         for ix,step in enumerate(retv[1:]):
382|             print('[%3d]: %s' % (ix+1,step))
383|             Log.debug('[%3d]: %s' % (ix+1,step))
384|         print('FINAL: %s' % retv[-1])
385|         Log.info('FINAL: %s' % retv[-1])
386|     else:
387|         print('RESULT: %s' % retv)
388|         Log.info('RESULT: %s' % retv)
389|     # Done...
390|     Log.info()
391|     return 'Done'
392| ##================================================================================================##
393| def do_calc_e_imag (**kwargs):
394|     """\
394| CMND: Calculate specified resolutions of (complex) e using (1+i/n)^n.
394| 
394| Takes N, the number of times to iterate (i.e. the power).
394| 
394| Converging on: exp(i)=(0.5403023058681398, +0.8414709848078965i)
394| """

395|     n = KWARG('n', 20, int, kwargs)
396|     Log.info('calculate-e-imag:: %s' % str(list(kwargs.keys())))
397|     Log.debug('n=%d' % n)
398|     Log.info()
399| 
400|     retv = calc_e_imag_n(n, capture_steps=1)
401|     Log.info('exp(i)=%s' % exp_eye)
402|     Log.info()
403|     if isinstance(retv,list):
404|         print('START: %s' % zstr(retv[0]))
405|         Log.debug('START: %s' % zstr(retv[0]))
406|         for ix,step in enumerate(retv[1:]):
407|             print('[%3d]: %s' % (ix+1,zstr(step)))
408|             Log.debug('[%3d]: %s' % (ix+1,zstr(step)))
409|         print('FINAL: %s' % zstr(retv[-1]))
410|         Log.info('FINAL: %s' % zstr(retv[-1]))
411|     else:
412|         print('RESULT: %s' % zstr(retv))
413|         Log.info('RESULT: %s' % zstr(retv))
414|     # Done...
415|     Log.info()
416|     return 'Done'
417| 
418| ##================================================================================================##
419| def do_calc_e_real_demo (**kwargs):
420|     """\
420| CMND: Calculate specified different resolutions of (real) e using (1+1/n)^n.
420| 
420| Converging on: exp(1)=2.718281828459
420| 
420| Example data:
420|     n=0 e=1.000000000000 diff=+1.718281828e+00 n=0 (0.000000000 secs)
420|     n=1 e=2.000000000000 diff=+7.182818285e-01 n=1 (0.000000000 secs)
420|     p=2 e=2.704813829422 diff=+1.346799904e-02 n=100 (0.000000000 secs)
420|     p=3 e=2.716923932236 diff=+1.357896223e-03 n=1000 (0.015625000 secs)
420|     p=4 e=2.718145926825 diff=+1.359016341e-04 n=10000 (0.000000000 secs)
420|     p=5 e=2.718268237192 diff=+1.359126675e-05 n=100000 (0.000000000 secs)
420|     p=6 e=2.718280469096 diff=+1.359363109e-06 n=1000000 (0.046875000 secs)
420|     p=7 e=2.718281694132 diff=+1.343270348e-07 n=10000000 (0.515625000 secs)
420|     p=8 e=2.718281798346 diff=+3.011268523e-08 n=100000000 (5.140625000 secs)
420|     p=9 e=2.718282052012 diff=-2.235528545e-07 n=1000000000 (53.015625000 secs)
420| 
420| """

421|     fpath = KWARG('fpath', BasePath, str, kwargs)
422|     fname = KWARG('fname', 'calc-e-real.out', str, kwargs)
423|     max_power = KWARG('p', 7, int, kwargs)
424|     Log.info('demo-calculate-e-real-demo:: %s' % str(list(kwargs.keys())))
425|     Log.debug('fpath="%s"' % fpath)
426|     Log.debug('fname="%s"' % fname)
427|     Log.debug('max-power=%d' % max_power)
428|     Log.info()
429|     print()
430|     filename = path.join(fpath, fname)
431| 
432|     Log.info('exp(1)=%.12f' % r_exp(1))
433|     Log.info('e=%.12f' % e)
434|     Log.info()
435|     calc_e_real_n(0)
436|     calc_e_real_n(1)
437|     for p in range(2, max_power+1):
438|         calc_e_real_pow(p)
439|     # Done...
440|     Log.info()
441|     return 'Done'
442| ##================================================================================================##
443| def do_calc_e_imag_demo (**kwargs):
444|     """\
444| CMND: Calculate specified resolutions of (complex) e using (1+i/n)^n.
444| 
444| Converging on: exp(i)=(0.5403023058681398, +0.8414709848078965i)
444| 
444| Example data:
444|     n=0 e=(+1.000000, +0.000000i) diff=(-4.596977e-01, +8.414710e-01i) n=0 (0.000000000 secs)
444|     n=1 e=(+1.000000, +1.000000i) diff=(-4.596977e-01, -1.585290e-01i) n=1 (0.000000000 secs)
444|     p=2 e=(+0.543039, +0.845671i) diff=(-2.736328e-03, -4.199580e-03i) n=100 (0.000000000 secs)
444|     p=3 e=(+0.540573, +0.841892i) diff=(-2.704992e-04, -4.206603e-04i) n=1000 (0.000000000 secs)
444|     p=4 e=(+0.540329, +0.841513i) diff=(-2.701860e-05, -4.207280e-05i) n=10000 (0.000000000 secs)
444|     p=5 e=(+0.540305, +0.841475i) diff=(-2.701546e-06, -4.207347e-06i) n=100000 (0.015625000 secs)
444|     p=6 e=(+0.540303, +0.841471i) diff=(-2.701515e-07, -4.207355e-07i) n=1000000 (0.093750000 secs)
444|     p=7 e=(+0.540302, +0.841471i) diff=(-2.701514e-08, -4.207369e-08i) n=10000000 (1.078125000 secs)
444|     p=8 e=(+0.540302, +0.841471i) diff=(-2.701576e-09, -4.207077e-09i) n=100000000 (11.390625000 secs)
444|     p=9 e=(+0.540302, +0.841471i) diff=(-2.701208e-10, -4.207334e-10i) n=1000000000 (118.734375000 secs)
444| 
444| """

445|     fpath = KWARG('fpath', BasePath, str, kwargs)
446|     fname = KWARG('fname', 'calc-e-imag.out', str, kwargs)
447|     max_power = KWARG('p', 7, int, kwargs)
448|     Log.info('calculate-e-imag-demo:: %s' % str(list(kwargs.keys())))
449|     Log.debug('fpath="%s"' % fpath)
450|     Log.debug('fname="%s"' % fname)
451|     Log.debug('max-power=%d' % max_power)
452|     Log.info()
453|     print()
454|     filename = path.join(fpath, fname)
455| 
456|     Log.info('exp(i)=%s' % exp_eye)
457|     Log.info()
458|     calc_e_imag_n(0)
459|     calc_e_imag_n(1)
460|     for p in range(2, max_power+1):
461|         calc_e_imag_pow(p)
462|     # Done...
463|     Log.info()
464|     return 'Done'
465| 
466| ##================================================================================================##
467| ## PASCAL'S TRIANGLE COEFFICIENTS
468| ##================================================================================================##
469| def do_calc_e_triangle_float (**kwargs):
470|     """\
470| Calculate approximation of e using numerators from row of Pascal's Triangle.
470| (Obsolete: use Fraction version)
470| """

471|     fpath = KWARG('fpath', BasePath, str, kwargs)
472|     fname = KWARG('fname', 'calc-e-tri-0.out', str, kwargs)
473|     levels = KWARG('n', 5, int, kwargs)
474|     which = KWARG('which', -1, int, kwargs)
475|     Log.info('calc-e-with-pascals-triangle-float:: %s' % str(list(kwargs.keys())))
476|     Log.debug('fpath="%s"' % fpath)
477|     Log.debug('fname="%s"' % fname)
478|     Log.debug('levels=%d' % levels)
479|     Log.debug('which=%d' % which)
480|     Log.info()
481|     filename = path.join(fpath, fname)
482|     # Generate the triangle and select a row...
483|     if levels < which: levels = which
484|     triangle = pascal_triangle(levels)
485|     tri_row = triangle[which][0]
486|     Log.info('triangle-levels=%d' % len(triangle))
487|     Log.debug(triangle[0][0])
488|     Log.debug(tri_row)
489|     Log.debug(triangle[-1][0])
490|     Log.info()
491|     # Use the triangle row as coefficients...
492|     print()
493|     n = len(tri_row)
494|     total = 0.0
495|     for ix,num in enumerate(tri_row):
496|         den = pow(n-1,ix)
497|         term = num / den
498|         total += term
499|         out = '%2d: %.12e %d/%d' % (ix,term,num,den)
500|         print(out)
501|         Log.trace(out)
502|     Log.trace()
503|     # Print result...
504|     print()
505|     print(total)
506|     Log.info(total)
507|     # Done...
508|     Log.info()
509|     return 'Done'
510| 
511| ##================================================================================================##
512| def do_calc_e_triangle_fraction (**kwargs):
513|     """\
513| Calculate approximation of e using numerators from row of Pascal's Triangle.
513| 
513| This version uses Fraction objects and doesn't generate a real number result
513| until the final step. And it returns the exact fraction result.
513| """

514|     fpath = KWARG('fpath', BasePath, str, kwargs)
515|     fname = KWARG('fname', 'calc-e-tri-1.out', str, kwargs)
516|     levels = KWARG('n', 5, int, kwargs)
517|     which = KWARG('which', -1, int, kwargs)
518|     Log.info('calc-e-with-pascals-triangle-fraction:: %s' % str(list(kwargs.keys())))
519|     Log.debug('fpath="%s"' % fpath)
520|     Log.debug('fname="%s"' % fname)
521|     Log.debug('levels=%d' % levels)
522|     Log.debug('which=%d' % which)
523|     Log.info()
524|     filename = path.join(fpath, fname)
525|     # Generate the triangle and select a row...
526|     if levels < which: levels = which
527|     triangle = pascal_triangle(levels)
528|     tri_row = triangle[which][0]
529|     Log.info('triangle-levels=%d' % len(triangle))
530|     Log.debug(triangle[0][0])
531|     Log.debug(tri_row)
532|     Log.debug(triangle[-1][0])
533|     Log.info()
534|     # Use the triangle row as coefficients...
535|     print()
536|     n = len(tri_row)
537|     total = Fraction(0)
538|     for ix,num in enumerate(tri_row):
539|         den = pow(n-1,ix)
540|         term = Fraction(num, den)
541|         total += term
542|         out = '%2d: %.12e %d/%d' % (ix,float(term),num,den)
543|         print(out)
544|         Log.trace(out)
545|     Log.trace()
546|     # Print result...
547|     print()
548|     print(total)
549|     print(float(total))
550|     print()
551|     Log.info(total)
552|     Log.info(float(total))
553|     # Done...
554|     Log.info()
555|     return 'Done'
556| 
557| ##================================================================================================##
558| def do_calc_e_triangle_complex (**kwargs):
559|     """\
559| Calculate approximation of e using numerators from row of Pascal's Triangle.
559| 
559| This version calculates the complex version (1+i)^n for some n.
559| """

560|     fpath = KWARG('fpath', BasePath, str, kwargs)
561|     fname = KWARG('fname', 'calc-e-tri-2.out', str, kwargs)
562|     levels = KWARG('n', 5, int, kwargs)
563|     which = KWARG('which', -1, int, kwargs)
564|     Log.info('calc-e-with-pascals-triangle-complex:: %s' % str(list(kwargs.keys())))
565|     Log.debug('fpath="%s"' % fpath)
566|     Log.debug('fname="%s"' % fname)
567|     Log.debug('levels=%d' % levels)
568|     Log.debug('which=%d' % which)
569|     Log.info()
570|     filename = path.join(fpath, fname)
571|     # Generate the triangle and select a row...
572|     if levels < which: levels = which
573|     triangle = pascal_triangle(levels)
574|     tri_row = triangle[which][0]
575|     Log.info('triangle-levels=%d' % len(triangle))
576|     Log.debug(triangle[0][0])
577|     Log.debug(tri_row)
578|     Log.debug(triangle[-1][0])
579|     Log.info()
580|     # Use the triangle row as coefficients...
581|     print()
582|     n = len(tri_row)
583|     real = Fraction(0)
584|     imag = Fraction(0)
585|     for ix,num in enumerate(tri_row):
586|         sgn = (-1 if (1 < (ix % 4)) else +1)
587|         den = pow(n-1,ix)
588|         term = Fraction(sgn*num, den)
589|         if (ix % 2) == 0:
590|             real += term
591|         else:
592|             imag += term
593|         out = '%2d: %+.12e %+d/%d' % (ix,float(term),sgn*num,den)
594|         Log.trace(out)
595|         print(out)
596|     Log.trace()
597|     # Print result...
598|     t0 = (*real.as_integer_ratio(), *imag.as_integer_ratio())
599|     t1 = (float(real), float(imag))
600|     print()
601|     print('((%d/%d), (%d/%d)i)' % t0)
602|     print('(%.12f, %.12fi)' % t1)
603|     print()
604|     Log.info('((%d/%d), (%d/%d)i)' % t0)
605|     Log.info('(%.12f, %.12fi)' % t1)
606|     # Done...
607|     Log.info()
608|     return 'Done'
609| 
610| ##================================================================================================##
611| def do_calc_e_tri_cmplx_multi (**kwargs):
612|     """Do a special function."""
613|     fpath = KWARG('fpath', BasePath, str, kwargs)
614|     fname = KWARG('fname', 'test.out', str, kwargs)
615|     levels = KWARG('n', 10, int, kwargs)
616|     Log.info('special:: %s' % str(list(kwargs.keys())))
617|     Log.debug('fpath="%s"' % fpath)
618|     Log.debug('fname="%s"' % fname)
619|     Log.debug('levels=%d' % levels)
620|     Log.info()
621|     # Calculate first 10 complex approximations using Pascal's Triangle...
622|     for ix in range(levels):
623|         kwargs['n'] = str(levels)
624|         kwargs['which'] = str(ix)
625|         do_calc_e_triangle_complex(**kwargs)
626|     # Done...
627|     Log.info()
628|     return 'Done'
629| 
630| ##================================================================================================##
631| def do_list_pascals_triangle (**kwargs):
632|     """CMND: List Pascal's Triangle data structure."""
633|     fpath = KWARG('fpath', BasePath, str, kwargs)
634|     fname = KWARG('fname', 'pascal-tri.out', str, kwargs)
635|     levels = KWARG('n', 42, int, kwargs)
636|     Log.info('list-pascals-triangle:: %s' % str(list(kwargs.keys())))
637|     Log.debug('fpath="%s"' % fpath)
638|     Log.debug('fname="%s"' % fname)
639|     Log.debug('levels=%d' % levels)
640|     Log.info()
641|     # Output file...
642|     filename = path.join(fpath, fname)
643|     fout = linefile(filename)
644|     # Pascal's Triangle...
645|     triangle = pascal_triangle(levels)
646|     for row in triangle:
647|         s = '%s (%d)' % row
648|         fout.data.append(s)
649|         Log.info(s)
650|     fout.data.append('')
651|     Log.info()
652|     fout.save()
653|     # Done...
654|     Log.info()
655|     return 'Done'
656| 
657| ##================================================================================================##
658| def do_terms_loop_demo (**kwargs):
659|     """Do demo of iteration and recursive handling of terms."""
660|     fpath = KWARG('fpath', BasePath, str, kwargs)
661|     fname = KWARG('fname', 'test.out', str, kwargs)
662|     levels = KWARG('n', 99, int, kwargs)
663|     Log.info('test:: %s' % str(list(kwargs.keys())))
664|     Log.debug('fpath="%s"' % fpath)
665|     Log.debug('fname="%s"' % fname)
666|     Log.debug('levels=%d' % levels)
667|     Log.info()
668|     ts0 = [1]
669|     Terms = lambda ts:[(a+b) for a,b in zip(ts+[0],[0]+ts)]
670| 
671|     def terms_loop_iterate (n):
672|         acc = [ts0]
673|         for ix in range(n):
674|             acc.append(Terms(acc[-1]))
675|         return acc
676| 
677|     def terms_loop_recurse (n):
678|         if n == 0:
679|             ts = [ts0]
680|             return ts
681|         ts = terms_loop_recurse(n-1)
682|         return ts+[Terms(ts[-1])]
683| 
684|     ts = terms_loop_iterate(levels)
685|     Log.info()
686|     Log.info('TERMS(iterate):')
687|     for ix,t in enumerate(ts):
688|         Log.info('%2d: %s' % (ix,t))
689|     Log.info()
690| 
691|     tt = terms_loop_recurse(levels)
692|     Log.info()
693|     Log.info('TERMS(recurse):')
694|     for ix,t in enumerate(tt):
695|         Log.info('%2d: %s' % (ix,t))
696|     Log.info()
697| 
698|     # Done...
699|     Log.info()
700|     return 'Done'
701| ##================================================================================================##
702| def do_exp_tests (**kwargs):
703|     """Do exp() function tests."""
704|     fpath = KWARG('fpath', BasePath, str, kwargs)
705|     fname = KWARG('fname', 'test.out', str, kwargs)
706|     Log.info('exp-tests:: %s' % str(list(kwargs.keys())))
707|     Log.debug('fpath="%s"' % fpath)
708|     Log.debug('fname="%s"' % fname)
709|     Log.info()
710|     #
711|     wheel(steps=120, cycles=0.25)
712|     #
713|     compare_exp_and_approx(m=14)
714|     #
715|     converge_exp_and_approx(m=40, z=complex(0.75,0))
716|     #
717|     # Done...
718|     Log.info()
719|     return 'Done'
720| ##================================================================================================##
721| def do_exp_demo (**kwargs):
722|     """Do exp() demo."""
723|     fpath = KWARG('fpath', BasePath, str, kwargs)
724|     fname = KWARG('fname', 'test.out', str, kwargs)
725|     Log.info('test:: %s' % str(list(kwargs.keys())))
726|     Log.debug('fpath="%s"' % fpath)
727|     Log.debug('fname="%s"' % fname)
728|     Log.info()
729|     cpi = complex(pi,0)
730|     ipi = eye*cpi
731|     exp_eye_cpi = c_exp(eye*cpi)
732|     ang_ee_eye = atan2(exp_eye.imag, exp_eye.real)
733|     ang_ee_eye_cpi = atan2(exp_eye_cpi.imag, exp_eye_cpi.real)
734| 
735|     def test_accuracy (n):
736|         expn = EE(n)
737|         Log.info('exp%d(1)=%s' % (n,zstr(expn(one))))
738|         Log.info('exp%d(pi)=%s' % (n,zstr(expn(cpi))))
739|         Log.info('exp%d(i)=%s' % (n,zstr(expn(eye))))
740|         Log.info('exp%d(ipi)=%s' % (n,zstr(expn(ipi))))
741|         Log.info()
742| 
743|     Log.info('one=%s' % zstr(one))
744|     Log.info('pi= %s' % zstr(cpi))
745|     Log.info('eye=%s' % zstr(eye))
746|     Log.info('ipi=%s' % zstr(ipi))
747|     Log.info()
748|     Log.info('e^1 =%s' % zstr(c_exp(one)))
749|     Log.info('e^pi =%s' % zstr(c_exp(cpi)))
750|     Log.info('e^i =%s' % zstr(c_exp(eye)))
751|     Log.info('e^ipi=%s' % zstr(c_exp(ipi)))
752|     Log.info()
753| 
754|     Log.info('phase(e^i): %.6f (%.3f deg)' % (ang_ee_eye,degrees(ang_ee_eye)))
755|     Log.info('phase(e^ipi): %.6f (%.3f deg)' % (ang_ee_eye_cpi,degrees(ang_ee_eye_cpi)))
756|     Log.info()
757| 
758|     test_accuracy(5)
759|     test_accuracy(9)
760|     test_accuracy(15)
761|     test_accuracy(21)
762|     test_accuracy(42)
763| 
764|     # Done...
765|     Log.info()
766|     return 'Done'
767| ##================================================================================================##
768| def do_test (**kwargs):
769|     """Do a test."""
770|     fpath = KWARG('fpath', BasePath, str, kwargs)
771|     fname = KWARG('fname', 'test.out', str, kwargs)
772|     levels = KWARG('n', 9, int, kwargs)
773|     which = KWARG('which', -1, int, kwargs)
774|     Log.info('test:: %s' % str(list(kwargs.keys())))
775|     Log.debug('fpath="%s"' % fpath)
776|     Log.debug('fname="%s"' % fname)
777|     Log.debug('levels=%d' % levels)
778|     Log.debug('which=%d' % which)
779|     Log.info()
780|     calc = calc_e(levels)
781|     calc.prn_integers(which)
782|     print()
783|     calc.prn_tuples(which)
784|     calc.prn_terms_real(which)
785|     calc.prn_terms_imag(which)
786|     # Done...
787|     Log.info()
788|     return 'Done'
789| ####################################################################################################
790| def dispatch (cmd, **kwargs):
791|     """Dispatch to a module function based on CMD."""
792|     Log.info('CMD: %s' % cmd)
793|     for kw in kwargs:
794|         Log.debug('argument[%s]: %s' % (kw,kwargs[kw]))
795|     Log.info()
796|     if cmd == 'real': return do_calc_e_real(**kwargs)
797|     if cmd == 'imag': return do_calc_e_imag(**kwargs)
798|     if cmd == 'c:real': return do_calc_e_real_chart(**kwargs)
799|     if cmd == 'c:imag': return do_calc_e_imag_chart(**kwargs)
800|     if cmd == 'tri.multi': return do_calc_e_tri_cmplx_multi(**kwargs)
801|     if cmd == 'tri.cmplx': return do_calc_e_triangle_complex(**kwargs)
802|     if cmd == 'tri.frac': return do_calc_e_triangle_fraction(**kwargs)
803|     if cmd == 'tri.float': return do_calc_e_triangle_float(**kwargs)
804|     if cmd == 'demo:real': return do_calc_e_real_demo(**kwargs)
805|     if cmd == 'demo:imag': return do_calc_e_imag_demo(**kwargs)
806|     if cmd == '$tri': return do_list_pascals_triangle(**kwargs)
807|     if cmd == '$exp': return do_exp_tests(**kwargs)
808|     if cmd == '$loop': return do_terms_loop_demo(**kwargs)
809|     if cmd == 'demo': return do_exp_demo(**kwargs)
810|     if cmd == 'test': return do_test(**kwargs)
811|     return 'Nothing to do!'
812| ####################################################################################################
813| if __name__ == '__main__':
814|     print('autorun: %s' % argv[0])
815|     #Log.start(path.join(BasePath,LogFilenameTimestamp('calculate_e_%s.log')))
816|     Log.start(path.join(BasePath,'calculate_e.log'))
817|     Log.level(info())
818|     Log.info(argv[0])
819|     Log.info()
820|     cmd = argv[1] if 1 < len(argv) else CMND
821|     kwargs = ARGS
822|     for a in argv[2:]:
823|         nv = a.split('=', 1)
824|         kwargs[nv[0]] = (nv[1] if 1<len(nv) else '')
825|         Log.debug('%s: "%s"' % (nv[0], kwargs[nv[0]]))
826|     try:
827|         print('CMD: %s' % cmd)
828|         print()
829|         obj = dispatch(cmd, **kwargs)
830|         print()
831|         print(obj)
832|         Log.info()
833|         Log.info(obj)
834|     except:
835|         etype, evalue, tb = exc_info()
836|         ts = extract_tb(tb)
837|         Log.error()
838|         Log.error('%s: %s' % (etype.__name__,str(evalue)))
839|         Log.error()
840|         for t in ts[-5:]:
841|             Log.error('[%d] %s (%s)' % (t[1], t[2], t[0]))
842|             Log.error(' %s' % t[3])
843|             Log.error()
844|         raise
845|     finally:
846|         Log.end()
847| ####################################################################################################
848| '''eof'''
849|