pie.html


001| '''Pi.
001| 
001| [Numbers for Windows]
001| 24873.852984 (5 digits)
001| 24873.87396564 (8 digits)
001| 24873.8739940562664 (12 digits)
001| 24873.873994062546944830896 (20 digits)
001| 24873.8739940625469448518252514498104 (30 digits)
001| 24873.87399406254694485182525145379203591895896 (40 digits)
001| 24873.87399406254694485182525145379203591950843649233784815122130405636717841168836753732853312874609680504
001| --
001| R0: 24873.852984
001| R1: 24873.87396564
001| R2: 24873.8739940562664
001| R3: 24873.873994062546944830896
001| R4: 24873.8739940625469448518252514498104
001| R5: 24873.87399406254694485182525145379203591895896
001| R9: 24873.87399406254694485182525145379203591950843649233784815122130405636717841168836753732853312874609680504
001| --
001| 
001| 
001| Developer@Sonnack.com
001| January 2019
001| '''

002| ####################################################################################################
003| from sys import argv
004| from os import path
005| from datetime import datetime
006| from facts import Planets
007| ####################################################################################################
008| 
009| BasePath = r'C:\CJS\prj\Python\ws\math'
010| 
011| InputFile  = 'pi-digits.in'
012| OutputFile = 'pi.out'
013| 
014| EarthDiameter = 2.0 * Planets['earth']['radius']['mi']
015| 
016| Str2Digit = lambda s: (ord(s) - ord('0'))
017| Digit2Str = lambda n: chr(ord('0') + n)
018| 
019| 
020| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
021| class PiDigits (object):
022|     '''Pi Digits class.
022| 
022| An instance of this class loads N digits of pi into an array.
022| In that array, each digit is a number from zero to nine.
022| 
022| The instance also contains count and frequency tables generated
022| during the load. Character counts and frequency are the occurance
022| of digits in the string. Last Character counts and frequency have
022| 10 values for each digit, each value the count or frequency of a
022| possible digit following the current one.
022| 
022| The instance also has a sequences table with sequence lengths and
022| the number of times they appeared for each digit.
022| '''

023|     def __init__ (self, ndigits=0, fname=InputFile, fpath=BasePath):
024|         self.t0 = datetime.now()
025|         self.nd = ndigits
026|         self.fn = path.join(fpath, fname)
027|         self.lines = 0
028|         self.chars = 0
029|         # Digit frequency...
030|         self.charhist = [int(0)]*10
031|         self.charfreq = [float(0)]*10
032|         # Previous digit frequency...
033|         self.lasthist = [[int(0)]*10 for _ in range(10)]
034|         self.lastfreq = [[float(0)]*10 for _ in range(10)]
035|         # Sequence lengths...
036|         self.seqs = [{} for _ in range(10)]
037|         # LOAD DIGITS...
038|         self._load_digits()
039|         # Calculate digit frequencies...
040|         tot = float(len(self.digits))
041|         for ix,n in enumerate(self.charhist):
042|             self.charfreq[ix] = 10.0 * (float(n) / tot)
043|         # Calculate last-digit frequencies...
044|         for jx,arr in enumerate(self.lasthist):
045|             for ix,n in enumerate(arr):
046|                 self.lastfreq[jx][ix] = 100.0 * (float(n) / tot)
047|         # And we're done...
048|         self.t1 = datetime.now()
049| 
050|     def __iter__ (self): return iter(self.digits)
051|     def __len__ (self): return len(self.digits)
052|     def __getitem__ (self, ix): return self.digits[ix]
053|     def __str__ (self): return ''.join(['3', '.'] + [str(d) for d in self.digits])
054| 
055|     def _load_digits (self):
056|         '''Load pi digits from a text file.'''
057|         self.digits = []
058|         fp = open(self.fn, mode='r', encoding='utf-8')
059|         try:
060|             last_digit = None
061|             seq_length = 0
062|             # Read pi digits (line by line)...
063|             for txt in fp:
064|                 self.lines += 1
065|                 for ch in txt.strip():
066|                     self.chars += 1
067|                     digit = Str2Digit(ch)
068|                     self.digits.append(digit)
069|                     self.charhist[digit] += 1
070|                     # Previous digit counts...
071|                     if last_digit != None:
072|                         self.lasthist[digit][last_digit] += 1
073|                     # Sequence length counter...
074|                     if last_digit == digit:
075|                         seq_length += 1
076|                     else:
077|                         if 1 < seq_length:
078|                             if seq_length not in self.seqs[digit]:
079|                                 self.seqs[digit][seq_length] = 0
080|                             self.seqs[digit][seq_length] += 1
081|                         seq_length = 1
082|                     # Check if we've got enough digits...
083|                     if self.nd:
084|                         if self.nd <= len(self.digits):
085|                             return
086|                     last_digit = digit
087|         except:
088|             raise
089|         finally:
090|             fp.close()
091| 
092| 
093| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
094| class Multiplier (object):
095|     '''Multiplier class.
095| 
095| This class implements an arbitrary precision floating point number using
095| an array of digits (0-9). The array has the MSD in the [0] slot and the
095| LSD in the [-1] slot.
095| 
095| A decimal point member indicates how many of the digits are behind the
095| decimal point.
095| 
095| New instances are created by providing;
095|     - an array of digits and a DP value
095|     - a text string of digits (which may contain a decimal point)
095|     - an integer or float value
095| 
095| The class support (only) addition and multiplication. The intent is a
095| tool for ridiculous precision exploration of pi and a look at some deep
095| bits of the Mandelbrot (which also requires ridiculous precision).
095| 
095| Note this isn't intended in any way to be fast.
095| 
095| '''

096|     def __init__ (self, digits=[0], dp=0, value=None, text=None):
097|         self.dp = dp
098|         if text:
099|             self._text2digits(text)
100|         elif value:
101|             if float(value) - float(int(value)):
102|                 vtxt = '%f' % value
103|             else:
104|                 vtxt = '%d' % value
105|             self._text2digits(vtxt)
106|         else:
107|             self.digits = list(reversed(digits))
108|         self._trim_leading_zeros()
109|         self._trim_trailing_zeros()
110|         self._carry()
111|         if self.dp == len(self.digits):
112|             self.digits.append(0)
113| 
114|     def __call__ (self): return [str(_) for _ in reversed(self.digits)]
115|     def __iter__ (self): return iter(self.digits)
116|     def __len__ (self): return len(self.digits)
117|     def __getitem__ (self, ix): return self.digits[ix]
118| 
119|     def __add__ (self, other):
120|         dp = max(self.dp, other.dp)
121|         dif = self.dp - other.dp
122|         if dif < 0:
123|             a_lsd = [0] * -dif
124|             b_lsd = []
125|         elif 0 < dif:
126|             a_lsd = []
127|             b_lsd = [0] * +dif
128|         else:
129|             a_lsd = []
130|             b_lsd = []
131|         dif = (len(self.digits)-self.dp) - (len(other.digits)-other.dp)
132|         if dif < 0:
133|             a_msd = [0] * -dif
134|             b_msd = []
135|         elif 0 < dif:
136|             a_msd = []
137|             b_msd = [0] * +dif
138|         else:
139|             a_msd = []
140|             b_msd = []
141|         a = a_lsd + self.digits + a_msd
142|         b = b_lsd + other.digits + b_msd
143|         c = reversed([a+b for a,b in zip(a, b)])
144|         return Multiplier(digits=list(c), dp=dp)
145| 
146|     def __mul__ (self, other):
147|         dp = self.dp + other.dp
148|         _c = [0] * (len(self.digits)+len(other.digits)+1)
149|         for ax,da in enumerate(self.digits):
150|             for bx,db in enumerate(other.digits):
151|                 _c[ax+bx] += (da * db)
152|         return Multiplier(digits=list(reversed(_c)), dp=dp)
153| 
154|     def __str__ (self):
155|         ds = self()
156|         if self.dp:
157|             x = len(ds) - self.dp
158|             si = ''.join(ds[:x])
159|             sf = ''.join(ds[x:])
160|             return '%s.%s' % (si, sf)
161|         return ''.join(ds)
162| 
163|     def __repr__ (self):
164|         s = '{Multiplier:{dp:%d, digits:%s}}'
165|         t = (self.dp, reversed(self.digits))
166|         return s%t
167| 
168|     def _trim_leading_zeros (self):
169|         while ((1+self.dp) < len(self.digits)) and (self.digits[-1] == 0):
170|             self.digits.pop()
171| 
172|     def _trim_trailing_zeros (self):
173|         while (0 < self.dp) and (self.digits[0] == 0):
174|             self.digits.pop(0)
175|             self.dp -= 1
176| 
177|     def _carry (self):
178|         for ix in range(len(self.digits)-1):
179|             v = self.digits[ix]
180|             if 10 <= v:
181|                 self.digits[ix] = (v % 10)
182|                 self.digits[ix+1] += (v // 10)
183|         if 10 <= self.digits[-1]:
184|             v = self.digits[-1]
185|             self.digits[-1] = (v % 10)
186|             self.digits.append(v // 10)
187| 
188|     def _text2digits (self, text):
189|         dp = len(text) - text.find('.') - 1
190|         self.dp = dp if dp < len(text) else 0
191|         self.digits = [Str2Digit(_) for _ in reversed(text) if _.isdigit()]
192| 
193| 
194| ##================================================================================================##
195| def test_pi_object (n_digits, nth_digit, fname='pi-stats.out', fpath=BasePath):
196|     fn = path.join(fpath, fname)
197|     fp = open(fn, mode='w', encoding='utf-8')
198|     try:
199|         obj = PiDigits(n_digits)
200|         print(file=fp)
201|         print('number of digits: %d' % len(obj), file=fp)
202|         print('pi digit [%d]: %d' % (nth_digit, obj[nth_digit-1]), file=fp)
203|         print('elapsed time: %.2f seconds' % (obj.t1-obj.t0).total_seconds(), file=fp)
204| 
205|         print(file=fp)
206|         for dx,t in enumerate(zip(obj.charhist, obj.charfreq)):
207|             print('%d: %9d | %+.9f' % (dx,t[0],t[1]-1.0), file=fp)
208| 
209|         print(file=fp)
210|         for dx,t in enumerate(obj.lastfreq):
211|             s = ['%+.4f' % (n-1.0) for n in t]
212|             print('%d: %s' % (dx,s), file=fp)
213|         print(file=fp)
214|         for dx,t in enumerate(obj.lasthist):
215|             print('%d: %s' % (dx,t), file=fp)
216| 
217|         print(file=fp)
218|         for dx,d in enumerate(obj.seqs):
219|             print('Digit: %d' % dx, file=fp)
220|             for k in sorted(d):
221|                 print('|-%s: %s' % (k, d[k]), file=fp)
222| 
223|         print(file=fp)
224|         if len(obj) < 3000:
225|             print(obj, file=fp)
226|         print(file=fp)
227|     except:
228|         raise
229|     finally:
230|         fp.close()
231|     return obj
232| 
233| 
234| ##================================================================================================##
235| def do_pi_precision_compare (fname=OutputFile, fpath=BasePath):
236|     rad = Multiplier(value=EarthDiameter)
237|     p0 = Multiplier(text='3.14159')
238|     p1 = Multiplier(text='3.14159265')
239|     p2 = Multiplier(text='3.141592653589')
240|     p3 = Multiplier(text='3.14159265358979323846')
241|     p4 = Multiplier(text='3.141592653589793238462643383279')
242|     p5 = Multiplier(text='3.1415926535897932384626433832795028841971')
243|     p9 = Multiplier(text='3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679')
244| 
245|     r0 = p0 * rad
246|     r1 = p1 * rad
247|     r2 = p2 * rad
248|     r3 = p3 * rad
249|     r4 = p4 * rad
250|     r5 = p5 * rad
251|     r9 = p9 * rad
252| 
253|     fn = path.join(fpath, fname)
254|     fp = open(fn, mode='w', encoding='utf-8')
255|     try:
256|         print(file=fp)
257|         print('radius: %s' % rad, file=fp)
258|         print(file=fp)
259|         print('P0: %s' % p0, file=fp)
260|         print('P1: %s' % p1, file=fp)
261|         print('P2: %s' % p2, file=fp)
262|         print('P3: %s' % p3, file=fp)
263|         print('P4: %s' % p4, file=fp)
264|         print('P5: %s' % p5, file=fp)
265|         print('P9: %s' % p9, file=fp)
266|         print(file=fp)
267|         print('R0: %s' % r0, file=fp)
268|         print('R1: %s' % r1, file=fp)
269|         print('R2: %s' % r2, file=fp)
270|         print('R3: %s' % r3, file=fp)
271|         print('R4: %s' % r4, file=fp)
272|         print('R5: %s' % r5, file=fp)
273|         print('R9: %s' % r9, file=fp)
274|         print(file=fp)
275|     except:
276|         raise
277|     finally:
278|         fp.close()
279|     return 'Done'
280| 
281| ##================================================================================================##
282| def do_pi_stats (*args):
283|     print('pi-stats: %d' % len(args))
284|     n_digits = int(args[0]) if 0 < len(args) else 10000000
285|     nth_digit = int(args[1]) if 1 < len(args) else n_digits
286|     obj = test_pi_object(n_digits, nth_digit)
287|     print()
288|     return 'Done'
289| 
290| ##================================================================================================##
291| def do_radius_test (*args):
292|     print('radius: %d' % len(args))
293|     print()
294| 
295|     pi_digits = 80
296|     pi_obj = PiDigits(ndigits=pi_digits)
297|     pi_mul = Multiplier(digits=[3]+pi_obj.digits, dp=pi_digits)
298|     print('pi: %s' % pi_mul)
299| 
300|     diameter = Multiplier(value=EarthDiameter)
301|     print('diameter: %s miles' % diameter)
302| 
303|     segmnt = Multiplier(text='0.000000001') # one-billionth
304|     print('segment: %s' % segmnt)
305| 
306|     inches = Multiplier([6,3,3,6,0]) # 5280 * 12
307|     print('inches/mile: %s' % inches)
308| 
309|     answer = diameter * pi_mul
310|     print('circumference: %s miles' % answer)
311|     answer = answer * segmnt
312|     print('10E^-9: %s miles' % answer)
313|     answer = answer * inches
314|     print('In inches: %s' % answer)
315| 
316|     print()
317|     return 'Done'
318| '''
318| pi: 3.141592653589793238
318| diameter: 7917.6 miles
318| segment: 0.000000001
318| inches/mile: 63360
318| circumference: 24873.8739940625469411888 miles
318| 10E^-9: 0.0000248738739940625469411888 miles
318| In inches: 1.576008656263802974193722368
318| '''

319| 
320| ##================================================================================================##
321| def do_test (*args):
322|     print('test: %d' % len(args))
323|     print()
324|     obj = PiDigits()
325|     print('loaded: %d digits' % len(obj))
326|     print(obj.digits[0:10])
327|     spi = str(obj)
328|     del obj
329| 
330|     fn = path.join(BasePath, 'pi-seqs.list')
331|     fp = open(fn, mode='w', encoding='utf-8')
332|     try:
333|         for n in range(9999, 100000):
334|             print(n)
335|             seq = str(n)
336|             print('Looking for: %s' % seq, file=fp)
337|             cnt = spi.count(seq)
338|             print('> found: %d' % cnt, file=fp)
339|             if cnt:
340|                 print('> first: %d' % spi.index(seq), file=fp)
341|             print(file=fp)
342|     finally:
343|         fp.close()
344|     print()
345|     return 'Done'
346| ##================================================================================================##
347| def do_main (*args):
348|     print('main: %d' % len(args))
349|     n_digits = int(args[0]) if 0 < len(args) else 100
350|     obj = PiDigits(n_digits)
351|     print()
352|     print(obj)
353|     print()
354|     return 'Done'
355| ####################################################################################################
356| def dispatch (cmd, *args):
357|     print('command: %s' % cmd)
358|     print('arguments: %d' % len(args))
359|     if cmd == 'main': return do_main(*args)
360|     if cmd == 'test': return do_test(*args)
361|     if cmd == 'radius': return do_radius_test(*args)
362|     if cmd == 'stats': return do_pi_stats(*args)
363|     if cmd == 'comp': return do_pi_precision_compare(*args)
364|     return 'Nothing to do!'
365| ####################################################################################################
366| if __name__ == '__main__':
367|     print('autorun: %s' % argv[0])
368|     cmd = argv[1] if 1 < len(argv) else 'test'
369|     etc = argv[2:] if 2 < len(argv) else []
370|     obj = dispatch(cmd, *etc)
371|     print(obj)
372| ####################################################################################################
373| '''eof'''
374|