-
Notifications
You must be signed in to change notification settings - Fork 0
/
newmath.py
771 lines (727 loc) · 23.4 KB
/
newmath.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
'''
Module for advanced math functions
Intended for use with user interface, rather than computer processing
For computer processesing, use oldmath (in progress)
to do:
* make class for eqations to avoid splitting them up
-would have them as custom data types
* add filtering of pi out of radian measures. Also common square roots
-(generic remove_irrat(num, num_symbol)
'''
import cat
#import warnings
pisym = u'\u03C0'
sqrtsym = u'\u221A'
'''
class for factoring things
might move this to oldmath
'''
class factor(object):
def __init__(self):
import cat
'''
returns a list of factor tuples
set one to False to exculde one from the factor list
Setting both to False will return a single list of single factors
Ignore ignores the number and one.
'''
@classmethod
def factor(self, num, one=True, split=False):
facts = []
if one:
a = 1
else:
a = 2
for i in range(a, int(num**.5)+1):
if not num % i:
if not split:
facts.append((i, num/i))
else:
facts.append(i)
facts.append(num/i)
return facts
'''
checks if value is prime
'''
@classmethod
def isPrime(self, num):
import os
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Primes.txt'), 'r+') as f:
primes = [int(line.rstrip('\n')) for line in f]
if num not in primes:
for i in range(int(num**.5) + 1, 1, -1):
if not num%i:
return False
f.write('\n'+str(num))
return True
return True
'''
Used for writing primes to the list
'''
@classmethod
def writePrimes(self, num):
found = 0
for i in range(num+1):
found += int(factor.isPrime(i))
print('%s primes found' % found)
'''
returns a list of prime factors.
Should return a list with multiple instances of factors occuring multiple times
'''
@classmethod
def primeFactor(self, num):
facts = []
num2 = num
for i in range(2, int((num**.5)+1)):
print i
if not num2%i and factor.isPrime(i):
facts.append(i)
num2 /= i
while not num2%i:
print i
num2 /= i
facts.append(i)
return facts
'''
Class for fractions.
Contains methods for conversion to fractions, simplification of fractions
'''
class fraction(object):
def __init__(self, n, d):
import cat
import warnings
self.n = n
self.d = d
'''
simplifies a fraction given as a tuple
'''
def simplify(num):
print type(num)
n = num.n
d = num.d
#print factor.factor(n, one=False, split=True)
for i in cat.listf.compare(factor.factor(n, one=False, split=True), factor.factor(d, one=False, split=True)):
n /= i
d /= i
return num(n, d)
'''
converts decimal to fraction
returns tuple (numerator, denominator)
'''
@classmethod
def tofrac_old(cls, num):
cat.ctype(num, float, 'tofrac()')
num2 = num
count = 0
while not cat.oldmath.isint(num2):
num2 *= 10
count += 1
n = num2
d = 10**count
return type(cls(n, d))
#return cls(n, d).simplify()
'''
same as tofrac_old, using native implementaion
'''
@classmethod
def tofrac(cls, num):
n, d = num.as_integer_ratio()
return cls(n, d)
'''
Adds two fractions
'''
@classmethod
def add(self, f1, f2):
n1, d1 = totuple(f1)
n2, d2 = totuple(f2)
if n1 == n2:
return (n1+n2, d2)
else:
#multiplies deominators and gets fraction
nd = d1*d2
n1 *= d2
n2 *= d1
'''
gets a tuple of numerator, denominator from a fraciton object
'''
@classmethod
def totuple(self, num):
return num.n, num.d
'''
Returns a string of the fraction. Use for printing.
'''
@classmethod
def tostring(frac):
return frac[0]+'/'+frac(1)
'''
class for running regressions and giving the result
'''
class regression(object):
@classmethod
def __init__(self):
import numpy
'''
Standard regression
'''
def standreg(self, xs, ys, retdeg=False):
import numpy
deg = len(xs)-1
array = numpy.zeros((deg+1, deg+1))
for i, x in enumerate(xs):
for i2, __ in enumerate(array[i]):
array[i][i2] = x**(deg-i2)
A = numpy.matrix(array)
array = numpy.zeros((deg+1, 1))
for i, y in enumerate(ys):
array[i][0] = y
X = numpy.matrix(array)
B = A.I*X
coeffs = [float(i[0]) for i in B]
eq = ''
for i, c in enumerate(coeffs):
#use for comparison; apparently floats are too imprecise
cr = round(c, 2)
if c < 10**-10 and c > -(10**-10):
c = 0
if cr == 1:
eq += 'x**%s+' % (deg-i)
elif cr:
eq += '%s*x**%s+' % (float(c), deg-i)
#finds actual degree of equation
if c == deg:
deg -= 1
#formats equation to make more readable
eq = eq.rstrip('+')
eq = eq.replace('+-', '-')
if retdeg:
return eq, deg, coeffs
else:
return eq
'''
root regression
Only works in perfect cases: root(x)+c
otherwise returns inverse function (x=y**5+y**2+5)
'''
@classmethod
def rootreg(self, xs, ys):
eq, deg, coeffs = reg(ys, xs, True)
eq = eq.replace('x', 'y')
#perform limited 'algebra'
if eq.count('y') == 1:
c = str(coeffs[len(coeffs)-1-deg])
c = '' if round(float(c), 2) == 1 else c
eqt = eq.split('+')
eql = eq.split('*')
r = eqt[len(eqt)-1] if eqt[len(eqt)-1] == eql[len(eql)-1] else 0
if r:
return str(c)+'x**(1/'+str(deg)+')+'+r
else:
return str(c)+'x**(1/'+str(deg)+')'
else:
return eq
'''
sine regression
Only works for flat functions (midline y=constant)
Other types in progress
Input points MUST be on same curve (between two midline intersections with
HIGH vertex inbetween)
VERY imprecise (occasionaly precise to the tenth place; usually worse)
'''
@classmethod
def sinreg(self, xs, ys, outprecision=1):
import numpy
from math import pi
import cat
precision = 5
for i, x in enumerate(xs):
xs[i] = round(x, precision)
for i, y in enumerate(ys):
ys[i] = round(y, precision)
del x
del y
#get quadratic curve from hich to derive vertexes midline, and period (find width between intersections
A = numpy.matrix([[xs[0]**2, xs[0], 1],
[xs[1]**2, xs[1], 1],
[xs[2]**2, xs[2], 1]])
X = numpy.matrix([[ys[0]], [ys[1]], [ys[2]]])
B = A.I*X
a = round(B[0, 0], precision)
b = round(B[1, 0], precision)
c = round(B[2, 0], precision)
#can evaluate this with different numbers by changing x
#positive c to reflect around midline instead of x-axis
f1 = '%s*x**2+%s*x+%s' % (a, b, c)
f2 = '%s*x**2+%s*x+%s' % (-a, -b, c)
#midlines
#solves for intesrection
#can do this because functions are fliped around midline. Remove c to flip around midline, intersection
#is midline
#QE
#does not account for phase shift
#might not need to
x1 = 0
x2 = round((-2*b)/(2*a), precision)
x=0
y1 = round(eval(f1), precision)
x = x2
y2 = round(eval(f1), precision)
#possibly find the equation mathich y1 and y2 to find a linier midline
assert round(y1, 3) == round(y2, 3), 'Midline is not flat. Non-flat midlines not yet supported. y1=%s. y2=%s' %(y1, y2)
#y=asin(b(x+c))+d
newd = y1
period = round(abs(x1-x2)*2, precision)
#period seems to be wildly imprecise, this is an attempt
#to ensure it is not 2pi
if round(period, 1) == round(2*pi, 1):
newb = 1
else:
newb = abs(x1-x2)*2.0 #real be = 2pi/this
#find vertexes
h = (-b)/(2*a)
x = h
k = eval(f1)
newa = abs(k-newd)
#phase shift
newc = (period/4.0 - h)
#formats equation
coeffs = [newa, newb, newc, newd]
for i, co in enumerate(coeffs):
coeffs[i] = round(co)
newa, newb, newc, newd = coeffs
eq = ''
if newa != 1:
eq += str(newa)
eq += 'sin('
roundb = round(2*pi/newb, 1)
if newb != 1 and newb != round(2*pi, precision) and not cat.oldmath.closeint((2*pi)/newb, .1) and not cat.oldmath.isfrac(roundb):
eq += '2pi/'+str(newb)+'('
elif cat.oldmath.closeint((2*pi)/newb, .1) or cat.oldmath.isfrac(roundb):
eq += str(round((2*pi)/newb, outprecision))+'('
## elif newb == 1:
## eq += '2pi('
z = numpy.sign(newc)
newc = round(newc, precision)%(period/2) #takes remainder becase a c larger than the period would be pointless
newc *= z
if newc != 0:
if newc > 0:
eq += 'x + '+str(newc)
else:
eq += 'x '+str(newc)
else:
eq += 'x'
if newb != 1 and newb != round(2*pi, precision):
eq += ')'
eq += ')'
if newd != 0:
if newd > 0:
eq += '+'+str(newd)
else:
eq += str(newd)
return eq#, newa, newb, newc, newd
'''
cosine regression
see notes under sine regressions
'''
@classmethod
def cosreg(self, xs, ys, outprecision=1):
import numpy
from math import pi
import cat
precision = 5
for i, x in enumerate(xs):
xs[i] = round(x, precision)
for i, y in enumerate(ys):
ys[i] = round(y, precision)
del x
del y
#get quadratic curve from hich to derive vertexes midline, and period (find width between intersections
A = numpy.matrix([[xs[0]**2, xs[0], 1],
[xs[1]**2, xs[1], 1],
[xs[2]**2, xs[2], 1]])
X = numpy.matrix([[ys[0]], [ys[1]], [ys[2]]])
B = A.I*X
a = B[0, 0]
b = B[1, 0]
c = B[2, 0]
#can evaluate this with different numbers by changing x
#positive c to reflect around midline instead of x-axis
f1 = '%s*x**2+%s*x+%s' % (a, b, c)
f2 = '%s*x**2+%s*x+%s' % (-a, -b, c)
#midlines
#solves for intesrection
#can do this because functions are fliped around midline. Remove c to flip around midline, intersection
#is midline
#QE
#does not account for phase shift
#might not need to
x1 = 0
x2 = (-2*b)/(2*a)
x=0
y1 = eval(f1), precision
x = x2
y2 = eval(f1), precision
#possibly find the equation mathich y1 and y2 to find a linier midline
assert round(y1, 3) == round(y2, 3), 'Midline is not flat. Non-flat midlines not yet supported. y1=%s. y2=%s' %(y1, y2)
#y=asin(b(x+c))+d
newd = y1
period = abs(x1-x2)*2
#period seems to be wildly imprecise, this is an attempt
#to ensure it is not 2pi
if round(period, 1) == round(2*pi, 1):
newb = 1
else:
newb = abs(x1-x2)*2.0 #real be = 2pi/this
#find vertexes
h = (-b)/(2*a)
x = h
k = eval(f1)
newa = abs(k-newd)
#phase shift
newc = -h
#formats equation
coeffs = [newa, newb, newc, newd]
for i, co in enumerate(coeffs):
coeffs[i] = round(co, outprecision)
newa, newb, newc, newd = coeffs
eq = ''
if newa != 1:
eq += str(newa)
eq += 'cos('
roundb = round(2*pi/newb, 1)
print roundb
if newb != 1 and newb != round(2*pi, precision) and not cat.oldmath.closeint((2*pi)/newb, .1) and not cat.oldmath.isfrac(roundb):
eq += '2pi/'+str(newb)+'('
elif cat.oldmath.closeint((2*pi)/newb, .1) or cat.oldmath.isfrac(roundb):
eq += str(round((2*pi)/newb, outprecision))+'('
## elif newb == 1:
## eq += '2pi('
z = numpy.sign(newc)
newc = round(newc, precision)%(period/2) #takes remainder becase a c larger than the period would be pointless
newc *= z
if newc != 0:
if newc > 0:
eq += 'x + '+str(newc)
else:
eq += 'x '+str(newc)
else:
eq += 'x'
if newb != 1 and newb != round(2*pi, precision):
eq += ')'
eq += ')'
if newd != 0:
if newd > 0:
eq += '+'+str(newd)
else:
eq += str(newd)
return eq#, newa, newb, newc, newd
'''
class for taking irrational numbers out of equations
Only can do division for now
Exponents coming later
'''
class Irrational(object):
@classmethod
def __init__(self, num, symbol=None):
self.num = num
if symbol == None:
symbol = str(num)
self.symbol = symbol
'''
pi
'''
def rempi(self,useunicode=True):
from math import pi
pic = u'\u03c0'
n = self.num
if not n%pi:
n2 = n/pi
if not cat.oldmath.isint(n2):
n2 = fraction.tostring(fraction.tofrac(n2))
#would need to determine if an even root can be taken here,
#then take it if nessesary
if useunicode:
return u'\u03c0*'+n2
else:
return 'pi*'+n2
'''
e
'''
def reme(self, n):
if not n%e:
n2 = n/e
if not cat.oldmath.isint(n2):
n2 = fraction.tostring(fraction.tofrac(n2))
return 'e*'+n2
def __str__
'''
class for equations
Makes equation objects
'''
class equation(object):
# @classmethod
def __init__(self, eq, ops=None):
if not ops:
self.declaredops = []
ops = ['+', '-', '/', '%', '*', '(', ')', '=', '**']
else:
self.declaredops = ops
self.string = eq
self.ops = equation.getops(ops)
self.nonops = equation.getnonops(ops)
'''
returns a list of the operators in the equation, in order
'''
# @classmethod
def getops(self, ops=['+', '-', '/', '%', '*', '(', ')', '=', '^']):
oplist = []
for char in self.split(ops):
if char in ops:
oplist.append(char)
return oplist
'''
like getops, but a generator
'''
# @classmethod
def getopsgen(self, ops=['+', '-', '/', '%', '*', '(', ')', '=', '^']):
for char in self.split(ops):
if char in ops:
yield char
'''
gets everything but the operators, in order
'''
# @classmethod
def getnonops(self, ops=['+', '-', '/', '%', '*', '(', ')', '=', '^']):
oplist = []
for char in self.split(ops):
if char not in ops:
oplist.append(char)
return oplist
'''
like getops, but a generator
'''
#S @classmethod
def getnonopsgen(self, ops=['+', '-', '/', '%', '*', '(', ')', '=', '^']):
for char in self.split(ops):
if char not in ops:
yield char
'''
Splits an equation into a list of numbers/variables and operators
Returns a list
Note: place multi-charecter operators first in the list
'''
# @classmethod
def split(self, ops=['+', '-', '/', '%', '*', '(', ')', '=', '^']):
import fnmatch
import cat
from cat import listf
init = ops[0]
ops = ops[1:]
#first operator is a special case. '+' is used
e = self.string.replace('**', '^').split(init)
for i, c in enumerate(e):
e[i] = [c, init]
e = listf.flatten(e)
del e[len(e)-1]
for op in ops:
for i, l in enumerate(e):
if op in l:
l = l.split(op)
for i2, c in enumerate(l):
l[i2] = [c, op]
l = listf.flatten(l)
del l[len(l)-1]
e[i] = l
e = listf.flatten(e)
#removes blank strings that seem to appear
e2 = []
skip = False
for char in e:
if char:
e2.append(char)
#replaces ^ with ** (** was replaced with ^ to prevent splitting into 2 *s)
for i, char in enumerate(e2):
if char == '^':
e2[i] = '**'
return e2
'''
takes an equation in Python syntax and
puts it in standard syntax
Not yet finished
Currently requires that all exponents have thier bases parenthetsized - (5)**4
Call as equationobject.format()
'''
# @classmethod
def format(self):
import re
import listf
import fnmatch
e = self
e = e.split()
for i, char in enumerate(e):
if char == '+' or char == '-':
try: a = int(e[i-1]) == 0
except (IndexError, ValueError):
pass
else:
if a:
e[i] = ''
e[i-1] = ''
e[i] = ' %s ' % char
elif char == '**':
e[i] = '^'
elif char == '*':
try: a = int(e[i-1]) == 1
except (IndexError, ValueError):
pass
else:
if a:
e[i] = ''
e[i-1] = ''
#add any additional charecters here
#put parenthesise logic below root logic
else:
try: a = int(char) == 0 and '+' in e[i+1]#e[i+1] == '+' or e[i+1] == ' + '
except (IndexError, ValueError):
pass
else:
if a:
e[i] = ''
e[i+1] = ''
else:
try: a = int(char) == 1 and e[i+1] == '*'#'*' in e[i+1] and '**' not in e[i+1]
except (IndexError, ValueError):
pass
else:
if a:
e[i] = ''
e[i+1] = ''
e = ''.join(e)
#Root logic:
#parenthesis framing pattern to include removed charecters
e = re.split(r'(\([^\)]+\)\^\([^/]+/[^\)]+\))', e)
e = listf.rstrip('', e)
for i, val in enumerate(e):
#would be better if there were an re.equals()
if re.search(r'(\([^\)]+\)\^\([^/]+/[^\)]+\))', val):
#val = listf.string.split(val, '^')
val = val.split('^')
base = val[0][1:len(val[0])-1] #strips leading and ending parenthesis
exp, root = val[1].split('/')
root = root[:len(root)-1] #strips last parenthese
exp = exp[1:]#strips leading parenthese
if float(root) == 2:
if float(exp) == 1:
e[i] = 'root(%s)' % base
else:
e[i] = 'root(%s^(%s))' % (base, exp)
elif float(exp) == 1:
e[i] = '%sroot(%s)' % (root, base)
else:
e[i] = '%sroot(%s^(%s))' % (root, base, exp)
#parenthese logic
e = ''.join(e)
e = equation(e).split()
for i, char in enumerate(e):
if char == '*' and e[i+1] == '(':
e[i] = ''
return ''.join(e)
def pyformat(self):
e = self.string
e = e.replace('^', '**')
#parenthesis filtering
#Parenthesis encolse pattern to add patterns found to the list of splits
esplit = re.split('([1-9]+\([^\)]+\))', '5(237+93)*1939+7(73)')
def evaluate(self):
return eval(pyformat(self))
#make reverse functions to take standard syntax and put in python syntax
#this stays at the bottom
def newmath():
from time import sleep as s
print 'New Math!',
s(.5)
print ' New-',
s(.15)
print 'hoo-',
s(.15)
print 'hoo',
s(.15)
print 'math'
#print
'''You can't take three from two,
Two is less than three,
So you look at the four in the tens place.
Now that's really four tens
So you make it three tens,
Regroup, and you change a ten to ten ones,
And you add 'em to the two and get twelve,
And you take away three, that's nine.
Is that clear?
Now instead of four in the tens place
You've got three,
'Cause you added one,
That is to say, ten, to the two,
But you can't take seven from three,
So you look in the hundreds place.
From the three you then use one
To make ten ones...
(And you know why four plus minus one
Plus ten is fourteen minus one?
'Cause addition is commutative, right!)...
And so you've got thirteen tens
And you take away seven,
And that leaves five...
Well, six actually...
But the idea is the important thing!
Now go back to the hundreds place,
You're left with two,
And you take away one from two,
And that leaves...?
Everybody get one?
Not bad for the first day!
Hooray for New Math,
New-hoo-hoo Math,
It won't do you a bit of good to review math.
It's so simple,
So very simple,
That only a child can do it!
Now, that actually is not the answer that I had in mind, because the book that I got this problem out of wants you to do it in base eight. But don't panic! Base eight is just like base ten really - if you're missing two fingers! Shall we have a go at it? Hang on...
You can't take three from two,
Two is less than three,
So you look at the four in the eights place.
Now that's really four eights,
So you make it three eights,
Regroup, and you change an eight to eight ones
And you add 'em to the two,
And you get one-two base eight,
Which is ten base ten,
And you take away three, that's seven.
Ok?
Now instead of four in the eights place
You've got three,
'Cause you added one,
That is to say, eight, to the two,
But you can't take seven from three,
So you look at the sixty-fours...
"Sixty-four? How did sixty-four get into it?" I hear you cry! Well, sixty-four is eight squared, don't you see? "Well, ya ask a silly question, ya get a silly answer!"
From the three, you then use one
To make eight ones,
You add those ones to the three,
And you get one-three base eight,
Or, in other words,
In base ten you have eleven,
And you take away seven,
And seven from eleven is four!
Now go back to the sixty-fours,
You're left with two,
And you take away one from two,
And that leaves...?
Now, let's not always see the same hands!
One, that's right.
Whoever got one can stay after the show and clean the erasers.
Hooray for New Math,
New-hoo-hoo Math!
It won't do you a bit of good to review math.
It's so simple,
So very simple,
That only a child can do it!
~Tom Lehrer'''