2023-09-10_calculating-the-number-e-in-python.html


001| #:name::Calculating the Number e (in Python)
002| #:link::https://thehardcorecoder.com/2023/09/10/calculating-the-number-e-in-python/
003| #:date::2023-09-10
004| #:code::
005| from fractions import Fraction
006| from math import e, factorial
007| 
008| def exp_factory (nbr_of_terms):
009|     def exp_function (x):
010|         terms = []
011|         for n in range(nbr_of_terms):
012|             term = Fraction(pow(x,n), factorial(n))
013|             terms.append(term)
014|         return float(sum(terms))
015|     return exp_function
016| 
017| fmt = '%3d: %.16f %.16e'
018| 
019| for nterms in [1,2,3,5,10,15,20,25]:
020|     # Get exp function using NT terms...
021|     exp_func = exp_factory(nterms)
022|     # Calculate exp(1)...
023|     approx_e = exp_func(1)
024|     print(fmt % (nterms, approx_e, e-approx_e))
025| print(' e: %.16f' % e)
026| print()
027| 
028| #:code::
029| def calc_e_real (n, capture_steps=0):
030|     tot = 1.0
031|     data = [tot]
032|     # Calculate...
033|     for ix in range(n):
034|         tot *= (1.0 + (1.0/n))
035|         if capture_steps: data.append(tot)
036|     return data if capture_steps else tot
037| 
038| def calc_e_imag (n, capture_steps=0):
039|     tot = complex(1,0)
040|     data = [tot]
041|     # Calculate...
042|     for ix in range(n):
043|         tot *= complex(1.0, 1.0/n)
044|         if capture_steps: data.append(tot)
045|     return data if capture_steps else tot
046| 
047| terms = 20
048| 
049| print(calc_e_real(terms, capture_steps=0))
050| print(calc_e_real(terms, capture_steps=1))
051| print()
052| print(calc_e_imag(terms, capture_steps=0))
053| print(calc_e_imag(terms, capture_steps=1))
054| print()
055| 
056| #:code::
057| from fractions import Fraction
058| 
059| def get_coefficients (depth=9):
060|     def next_row (row):
061|         left  = row + [0]
062|         right = [0] + row
063|         return [a+b for a,b in zip(left,right)]
064| 
065|     table = [[1]]
066|     for ix in range(depth):
067|         row = next_row(table[-1])
068|         table.append(row)
069|     return table
070| 
071| tab = get_coefficients(4)
072| row = tab[-1]
073| print(row)
074| print()
075| base = len(row) - 1
076| 
077| terms = [(n,base**ix) for ix,n in enumerate(row)]
078| for t in terms:
079|     print(repr(t))
080| print()
081| 
082| fracs = [Fraction(a,b) for a,b in terms]
083| for f in fracs:
084|     print(repr(f))
085| print()
086| 
087| value = float(sum(fracs))
088| print(value)
089| print()
090| 
091| #:code::
092| from fractions import Fraction
093| 
094| def get_coefficients (degree=9):
095|     '''Terms are tuples: (num,i_flag).'''
096|     def shift (term):
097|         # Return a shifted version of term...
098|         if term[1]:
099|             # Imaginary term: i^2 = -1...
100|             return (-term[0], 0)
101|         # Real term: becomes imaginary...
102|         return (term[0], 1)
103| 
104|     def adder (term_a, term_b):
105|         # Add the numeric terms...
106|         c0 = term_a[0] + term_b[0]
107|         # Set i_flag if set in A or B...
108|         c1 = 1 if (term_a[1] or term_b[1]) else 0
109|         return (c0, c1)
110| 
111|     def next_row (row):
112|         ts0  = row + [(0,0)]
113|         ts1 = [(0,0)] + [shift(t) for t in row]
114|         # Return ts0+ts1...
115|         return [adder(a,b) for a,b in zip(ts0,ts1)]
116| 
117|     table = [[(1,0)]]
118|     for ix in range(degree):
119|         row = next_row(table[-1])
120|         table.append(row)
121|     return table
122| 
123| tab = get_coefficients(4)
124| for row in tab:
125|     print(row)
126| print()
127| 
128| #:code::
129| from fractions import Fraction
130| 
131| def coeffs_2_nmbrs (coeffs, prn=False):
132|     nmbrs = [abs(c[0]) for c in coeffs]
133|     if prn:
134|         print(','.join([str(n) for n in nmbrs]))
135|         print()
136|     return nmbrs
137| 
138| def coeffs_2_tuples (coeffs, prn=False):
139|     denom = len(coeffs) - 1
140|     terms = []
141|     for ix,c in enumerate(coeffs):
142|         term = (c[0], pow(denom,ix))
143|         terms.append(term)
144|     if prn:
145|         for t in terms: print(t)
146|         print()
147|     return terms
148| 
149| def coeffs_2_terms_real (coeffs, prn=False):
150|     denom = len(coeffs) - 1
151|     terms = []
152|     for ix,c in enumerate(coeffs):
153|         term = Fraction(abs(c[0]), pow(denom,ix))
154|         terms.append(term)
155|     real_value = float(sum(terms))
156|     if prn:
157|         for t in terms: print(term2str(t))
158|         print('\n%.12f\n' % real_value)
159|     return (real_value, terms)
160| 
161| def coeffs_2_terms_imag (coeffs, prn=False):
162|     denom = len(coeffs) - 1
163|     real_terms = []
164|     imag_terms = []
165|     for ix,c in enumerate(coeffs):
166|         term = Fraction(c[0], pow(denom,ix))
167|         if c[1]:
168|             imag_terms.append(term)
169|         else:
170|             real_terms.append(term)
171|     real_value = float(sum(real_terms))
172|     imag_value = float(sum(imag_terms))
173|     z = complex(real_value, imag_value)
174| 
175|     xr,xi = list(real_terms), list(imag_terms)
176|     terms = []
177|     while 0 < (len(xr)+len(xi)):
178|         if 0 < len(xr): terms.append(xr.pop(0))
179|         if 0 < len(xi): terms.append(xi.pop(0))
180|     if prn:
181|         for t in terms: print(term2str(t))
182|         print()
183|     return (z, real_terms, imag_terms)
184| 
185| coeffs_list = get_coefficients(4, prn=False)
186| coeffs_row  = coeffs_list[-1]
187| 
188| coeffs_2_nmbrs(coeffs_row, prn=True)
189| coeffs_2_tuples(coeffs_row, prn=True)
190| 
191| coeffs_2_terms_real(coeffs_row, prn=True)
192| coeffs_2_terms_imag(coeffs_row, prn=True)
193| 
194| #:end:code::
195|