-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodegebra.py
2036 lines (1968 loc) · 83.3 KB
/
codegebra.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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math, cmath, random
import re
from scipy.linalg import lapack
from scipy.linalg import blas
import ast
import operator as op
import pandas as pd
import math
# supported operators(for safely running eval)
operators = {
ast.Add: op.add,
ast.Sub: op.sub,
ast.Mult: op.mul,
ast.Div: op.truediv,
ast.Pow: op.pow,
ast.BitXor: op.xor,
ast.USub: op.neg
}
#For matching exponentials
pattern = r'(-?[0-9.]+\s*=\s*(?:-?[0-9.]+\s*\*\s*)?-?[0-9.]+\^\(x[+-][0-9.]+\)(?:\s*[+-]\s*[0-9.]+)?)|(\s*(?:-?[0-9.]+\s*\*\s*)?-?[0-9.]+\^\(x[+-][0-9.]+\)(?:\s*[+-]\s*[0-9.]+)?=-?[0-9.]+\s*)'
reverse_pattern = r'(\s*(?:-?[0-9.]+\s*\*\s*)?-?[0-9.]+\^\(x[+-][0-9.]+\)(?:\s*[+-]\s*[0-9.]+)?=-?[0-9.]+\s*)'
ans = ""
ans_alt = ""
input_prim = input # move native input function so we can modify
round_prim = round # move native round function so we can modify
eps = 12 #Machine epsilon
def input(prompt):
global ans, ans_alt
# Reimplement python input function with support for ans
inp = input_prim(prompt) # Use primitive input to actually get the data
if type(ans) != str:
ans = str(ans)
if type(ans_alt) != str:
ans_alt = str(ans_alt)
inp = inp.replace("ANS2", ans_alt)
inp = inp.replace("ANS", ans)
return inp
def round(n, eps):
if type(n) == float or type(n) == int:
return round_prim(n, eps)
elif type(n) == complex:
return round_prim(n.real, eps) + round_prim(n.imag, eps) * 1j
def gcd(a, b):
if (a < b):
return gcd(b, a)
# base case
if (abs(b) < 0.001):
return a
else:
return (gcd(b, a - math.floor(a / b) * b))
def simplifyTerms(terms):
terms = [
item for item in terms
if item is not None and item not in [True, False]
]
x_coeff = 0 # X coefficient(aka m in y=mx+b)
x2_coeff = 0 # X^2 coefficient(aka A in ax^2+bx+c=0)
# Quadratic and exponential flags
is_quadratic = False
is_expo = "^(x" in "".join(terms)
const = 0 # Constant(aka b in y=mx+b)
# Variables in the exponential equation
y = 0
a = 0
b = 0
h = 0
k = 0
for term in terms:
if ("x" in term
or "X" in term) and (term.find("x**2") == -1
and term.find("x^2") == -1) and not is_expo:
# Take out the X to get the coefficient
term = term.replace("x", "")
term = term.replace("X", "")
if term == "":
# If it doesn't have a coefficient than set it to one
x_coeff += 1
elif term == "-":
# take away 1 if the coefficient is just a negative sign
x_coeff += -1
else:
x_coeff += float(
term) # If x has a coefficient then add it to the running tally
elif "x**2" in term or "x^2" in term:
is_quadratic = True
# Take out the X^2 to get the coefficient
term = term.replace("x**2", "")
term = term.replace("x^2", "")
if term == "":
# If it doesn't have a coefficient than set it to one
x2_coeff += 1
elif term == "-":
# take away 1 if the coefficient is just a negative sign
x2_coeff += -1
else:
x2_coeff += float(
term) # If x has a coefficient then add it to the running tally
elif is_expo:
if len(terms) == 1:
y = float(term)
elif re.findall(r'\d+\^\(', term) != []:
term = term.replace("^(", "")
term = term.replace("x", "")
if len(term.split("*")) == 2:
a = float(term.split("*")[0])
b = float(term.split("*")[1])
else:
b = float(term)
elif re.findall(r'\d\)', term):
h = float(term.replace(")", "")) * -1
else:
k = float(term)
# Take out the X^2 to get the coefficient
term = term.replace("x**2", "")
term = term.replace("x^2", "")
else:
const += float(term) # Add to the running tally for the constant
if x_coeff == 1:
x_coeff = ""
else:
x_coeff = str(x_coeff)
# If a is 0 in a quadratic, is it really a quadratic?
if x2_coeff == 1:
x2_coeff = "x^2"
elif x2_coeff == 0:
is_quadratic = False
x2_coeff = None
else:
x2_coeff = str(x2_coeff) + "x^2"
# Determine which return values should be set to null
if is_expo:
return [None, None, False, None, a, b, h, k]
if x_coeff == "0" and const != "0":
return [None, str(const), is_quadratic, x2_coeff]
elif x_coeff != "0" and const == "0":
return [None, None, is_quadratic, x2_coeff]
elif x_coeff == "0" and const == "0":
return [None, None, is_quadratic, x2_coeff]
else:
return [f"{x_coeff}x", str(const), is_quadratic, x2_coeff]
def simpStdForm(equation):
equation = equation.replace(" ", "") # Remove whitespace
# Equation mode
right, left = equation.split(
"=") # Split string into left and right sides of the equal sign
# Seperate terms on each side of the equation
left = " ".join(left.split("+"))
left = left.replace("-", " -")
right = " ".join(right.split("+"))
right = right.replace("-", " -")
right = right.split()
left = left.split()
x_coeff = 0
y_coeff = 0
const = 0
for term in right:
if ("x" in term) or ("X" in term):
# Take out the X to get the coefficient
term = term.replace("x", "")
term = term.replace("X", "")
if term == "":
# If it doesn't have a coefficient than set it to one
x_coeff -= 1
elif term == "-":
# take away 1 if the coefficient is just a negative sign
x_coeff += 1
else:
x_coeff -= float(
term) # If x has a coefficient then add it to the running tally
elif ("y" in term) or ("Y" in term):
# Take out the X to get the coefficient
term = term.replace("y", "")
term = term.replace("Y", "")
if term == "":
# If it doesn't have a coefficient than set it to one
y_coeff -= 1
elif term == "-":
# take away 1 if the coefficient is just a negative sign
y_coeff += 1
else:
y_coeff -= float(
term) # If y has a coefficient then add it to the running tally
else:
const -= float(term) # Add to the running tally for the constant
for term in left:
if ("x" in term) or ("X" in term):
# Take out the X to get the coefficient
term = term.replace("x", "")
term = term.replace("X", "")
if term == "":
# If it doesn't have a coefficient than set it to one
x_coeff += 1
elif term == "-":
# take away 1 if the coefficient is just a negative sign
x_coeff += -1
else:
x_coeff += float(
term) # If x has a coefficient then add it to the running tally
elif ("y" in term) or ("Y" in term):
# Take out the X to get the coefficient
term = term.replace("y", "")
term = term.replace("Y", "")
if term == "":
# If it doesn't have a coefficient than set it to one
y_coeff += 1
elif term == "-":
# take away 1 if the coefficient is just a negative sign
y_coeff += -1
else:
y_coeff += float(
term) # If y has a coefficient then add it to the running tally
else:
const += float(term) # Add to the running tally for the constant
return (x_coeff, y_coeff, const)
def parseEq(eq, eq_type="=", is_expo=False):
eq = eq.replace(" ", "") # Remove whitespace
if eq_type in ["=", "≥", "≤", ">", "<"]:
right, left = eq.split(
eq_type) # Split string into left and right sides of the equal sign
# Seperate terms on each side of the equation
if is_expo == False:
addition_pattern = r'\+(?![^(]*\))'#Don't split if its inside parentheses
subtraction_pattern = r'\-(?![^(]*\))'
else:
# It is ok if we split if it is inside parentheses for exponential equations
# Because the exponential solver expects it to be split
addition_pattern = r'(?<!\*)\+'
subtraction_pattern = r'(?<!\*)\-'
# We replace the operators with whitespace so when we split it into an array, we can easily see the barriers
# between the terms
left = " ".join(re.split(addition_pattern, left))
left = re.sub(subtraction_pattern, " -", left)
right = " ".join(re.split(addition_pattern, right))
right = re.sub(subtraction_pattern, " -", right)
right = right.split()
left = left.split()
def distribute_side(side):
for i in range(len(side)):
term = side[i]
if "(" in term:
if re.match(r"-?[0-9]\d*(\.\d+)?\((.*)\)", term):
coeff = term.split("(")[0]
inside = term.split("(")[1][:-1]
inside = " ".join(inside.split("+"))
inside = inside.replace("-", " -")
inside = inside.split()
for j in range(len(inside)):
if "x" in inside[j] and inside[j] != "x":
inside[j] = str(float(coeff) * float(inside[j][:-1]))+"x"
elif "x" == inside[j]:
inside[j] = coeff + "x"
else:
inside[j] = str(float(coeff) * float(inside[j]))
side[i:i + 1] = inside
elif term.split("(")[0][-1] == ")":
inside = side.split("(")[0]
inside = " ".join(inside.split("+"))
inside = inside.replace("-", " -")
inside = inside.split()
side[i:i + 1] = inside
if is_expo == False:
distribute_side(left)
distribute_side(right)
#Regularly split: ['4*2^(x', '-2)', '3']( 3=4*2^(x-2)+3 )
#When a or b is negative: ['4*', '-2^(x-2)', '3'] ( 3=4*-2^(x-2)+3 )
return simplifyTerms(right), simplifyTerms(left)
else:
# Expression mode
eq = " ".join(eq.split("+"))
eq = eq.replace("-", " -")
eq = eq.split()
return eq
def quadratic_formula(a, b, c):
discriminant = b ** 2 - (4 * a * c)
if discriminant >= 0:
x_1 = ((-1 * b) + math.sqrt(discriminant)) / (2 * a)
x_2 = ((-1 * b) - math.sqrt(discriminant)) / (2 * a)
else:
i_coeff = math.sqrt(
abs(discriminant)) # The coefficient of i if the solution is complex
if i_coeff >= 0:
# If the i coefficient is positive
if i_coeff / (2 * a) == 1:
# If it is one
x_1 = f"{(-1 * b) / (2 * a)}+i"
x_2 = f"{(-1 * b) / (2 * a)}-i"
else:
x_1 = f"{(-1 * b) / (2 * a)}+{i_coeff / (2 * a)}i"
x_2 = f"{(-1 * b) / (2 * a)}-{i_coeff / (2 * a)}i"
else:
# If the coefficient is negative
x_1 = f"{(-1 * b) / (2 * a)}{i_coeff / (2 * a)}i"
x_2 = f"{(-1 * b) / (2 * a)}+{(i_coeff / (2 * a)) * -1}i"
return x_1, x_2
def exponential_solver(y, a=1, b=None, h=0, k=0):
print(f"y={y}, a={a}, b={b}, h={h}, k={k}")
#https://www.wolframalpha.com/input?i=y-k%3Da*b%5E%28x-h%29+solve+for+x
imag_solution = None
log_b = cmath.log(b)
if k != y and a != 0 and log_b != complex(0, 0):
if log_b.imag == 0:
#If there is not an imaginary component then omit it from outputs
log_b = log_b.real
numerator = cmath.log(-a / (k - y)) - h * log_b
if numerator.imag == 0:
numerator = numerator.real
#I dont know why this works but it does
imag_solution = f"x = -({-numerator if numerator.real != 0 else str(numerator.imag)+"j"} + {2j*math.pi}n) / {-log_b}"
return imag_solution
def solve(equation):
global ans, ans_alt
eq_type = "="
if ">" in equation:
eq_type = ">"
elif "<" in equation:
eq_type = "<"
elif "≥" in equation:
eq_type = "≥"
elif "≤" in equation:
eq_type = "≤"
if "x**3" in equation or "x^3" in equation:
print("Cannot solve polynomials with a degree above 2")
return 0
if ("x**2" in equation) or ("x^2" in equation):
left, right = parseEq(equation, eq_type)
right_cpy = right.copy() # Copy the equation to avoid an infinite loop
# Move terms to left side of the equal sign
if right[0] is not None:
if "-" in right[0]:
# Add to both sides
right.append(right[0][1:])
left.append(right[0][1:])
else:
# Subtract from both sides
right.append("-" + str(right[0]))
left.append("-" + str(right[0]))
if right[1] != None:
if "-" in right[1]:
# Add to both sides
right.append(right[1][1:])
left.append(right[1][1:])
else:
# Subtract from both sides
right.append("-" + str(right[1]))
left.append("-" + str(right[1]))
if right[3] != None:
if "-" in right[3]:
print(right[3])
# Add to both sides
right.append(right[3][1:] + "x^2")
left.append(right[3][1:] + "x^2")
else:
# Subtract from both sides
right.append("-" + str(right[3]) + "x^2")
left.append("-" + str(right[3]) + "x^2")
right, left = simplifyTerms(right), simplifyTerms(left)
# Extract A, B, and C
left[3] = left[3].replace("x^2", "")
if left[3] == "":
a = 1
else:
a = float(left[3].replace("x^2", ""))
if left[0] == None:
b = 0
else:
b = float(left[0].replace("x", ""))
c = float(left[1])
x_1, x_2 = quadratic_formula(a, b, c) # Plug into the quadratic formula
if x_1 == x_2:
print(f"x {eq_type} {x_1}")
ans = x_1
else:
ans = x_1
ans_alt = x_2
print(f"x {eq_type} {x_1}")
print(f"x {eq_type} {x_2}")
elif re.findall(pattern, equation) != []:
if re.findall(reverse_pattern, equation) != []:
equation = equation.split("=")
equation = equation[1] + "=" + equation[0]
left, right = parseEq(equation, eq_type, is_expo=True)
imag_solution = exponential_solver(float(left[1]), right[4], right[5], right[6], right[7])
print(f"Imaginary solution: {imag_solution}")
print("n ∈ ℤ(ℤ is the set of integers)")
else:
left, right = parseEq(equation, eq_type)
# Goal: Get X on one side and the consts on the other side, then divide the coefficient by the constant
if right[0] != None:
# Isolate x on the left side of the equation
if "-" in right[0]:
# Add to both sides
right.append(right[0][1:])
left.append(right[0][1:])
else:
# Subtract from both sides
right.append("-" + str(right[0]))
left.append("-" + str(right[0]))
if right[1] != None:
# Isolate the constants on the right side
if "-" in left[1]:
# Add to both sides
right.append(left[1][1:])
left.append(left[1][1:])
else:
# Subtract from both sides
right.append("-" + str(left[1]))
left.append("-" + str(left[1]))
left, right = simplifyTerms(left), simplifyTerms(right)
if left[0] == "x":
x_coeff = 1
else:
x_coeff = float(left[0].replace("x", ""))
if eq_type != "=" and x_coeff < 0:
if eq_type == ">":
eq_type = "<"
elif eq_type == "<":
eq_type = ">"
elif eq_type == "≥":
eq_type = "≤"
elif eq_type == "≤":
eq_type = "≥"
const = float(right[1])
ans = const / x_coeff
print(f"x {eq_type} {const / x_coeff}")
def derivative(expression):
global ans, ans_alt
og_expression = expression
expression = parseEq(expression, "EXP")
new_expression = []
for term in expression:
if re.findall(r'(\d+(\*?))?x\^(\d+)', term):
# Power rule
term = term.split("x^")
if term[0] == "":
a = 1
else:
a = int(term[0])
b = int(term[1])
a = a * b
b = b - 1
if b == 1:
b = "x"
elif b == 0:
b = ""
else:
b = f"x^{b}"
if a == 1:
a = ""
term = f"{a}{b}"
new_expression.append(term)
# Special cases
elif term == "log x" or term == "log(x)":
new_expression.append("1/x")
elif term == "sin x" or term == "sin(x)":
new_expression.append("cos(x)")
elif term == "tan x" or term == "tan(x)":
new_expression.append("sec^2(x)")
elif term == "sinh x" or term == "sinh(x)":
new_expression.append("cosh(x)")
elif term == "cosh x" or term == "cosh(x)":
new_expression.append("sinh(x)")
elif term == "tanh x" or term == "tanh(x)":
new_expression.append("sech^2(x)")
elif term == "-acos x" or term == "-acos(x)" or term == "acos x" or term == "acos(x)" or term == "asin(x)" or term == "asin x":
new_expression.append("1/√(1-x^2)")
elif term == "atan x" or term == "atan(x)":
new_expression.append("1/(x^2-1)")
elif term == "acosh x" or term == "acosh(x)":
new_expression.append("1/√(x^2+1)*√(x^2-1)")
elif term == "asinh x" or term == "asinh(x)":
new_expression.append("1/√(x^2+1)")
elif term == "atanh x" or term == "atanh(x)":
new_expression.append("1/(1 - x^2)")
elif term == "sec^2 x" or term == "sec^2(x)":
new_expression.append("2*tan(x)*sec^2(x)")
elif term == "sech^2 x" or term == "sech^2(x)":
new_expression.append("-2*tanh(x)*sech^2(x)")
elif term == "e^x" or term == "e**x":
new_expression.append("e^x")
elif term == "1/x":
new_expression.append("-1/x^2")
elif term == "cos x" or term == "cos(x)":
new_expression.append("sin(x)")
elif term == "-log x" or term == "-log(x)":
new_expression.append("-1/x")
elif term == "-sin x" or term == "-sin(x)":
new_expression.append("-cos(x)")
elif term == "-tan x" or term == "-tan(x)":
new_expression.append("-sec^2(x)")
elif term == "-sinh x" or term == "-sinh(x)":
new_expression.append("-cosh(x)")
elif term == "-cosh x" or term == "-cosh(x)":
new_expression.append("-sinh(x)")
elif term == "-tanh x" or term == "-tanh(x)":
new_expression.append("-sech^2(x)")
elif term == "-asin(x)" or term == "-asin x":
new_expression.append("-1/√(1-x^2)")
elif term == "-atan x" or term == "-atan(x)":
new_expression.append("-1/(x^2+1)")
elif term == "-acosh x" or term == "-acosh(x)":
new_expression.append("-1/√(x^2+1)*√(x^2-1)")
elif term == "-asinh x" or term == "-asinh(x)":
new_expression.append("-1/√(x^2+1)")
elif term == "-atanh x" or term == "-atanh(x)":
new_expression.append("1/(x^2-1)")
elif term == "-sec^2 x" or term == "-sec^2(x)":
new_expression.append("-2*tan(x)*sec^2(x)")
elif term == "-sech^2 x" or term == "-sech^2(x)":
new_expression.append("2*tanh(x)*sech^2(x)")
elif term == "-e^x" or term == "-e**x":
new_expression.append("-e^x")
elif term == "-1/x":
new_expression.append("1/x^2")
elif term == "-cos x" or term == "-cos(x)":
new_expression.append("sin(x)")
elif re.findall(r'\d+(\*?)x', term) != []:
# Regular slope
if "*" in term:
new_expression.append(term[:-2])
else:
new_expression.append(term[:-1])
new_expression_str = ""
for term in new_expression:
if new_expression_str == "":
new_expression_str = term
else:
if term[0] == "-":
new_expression_str = new_expression_str + term
else:
new_expression_str = new_expression_str + "+" + term
ans = f"d/dx ({og_expression}) = " + new_expression_str
print(f"d/dx ({og_expression}) = " + new_expression_str)
def integrate(expression):
global ans, ans_alt
og_expression = expression
expression = parseEq(expression, "exp")
new_expression = []
for term in expression:
if re.findall(r'(\d+(\*?))?x\^(\d+)', term):
# Inverse power rule
term = term.split("x^")
if term[0] == "":
a = 1
else:
a = int(term[0])
b = int(term[1])
a = a / (b + 1)
b = b + 1
if b == 1:
b = "x"
elif b == 0:
b = ""
else:
b = f"x^{b}"
if a == 1:
a = ""
term = f"{a}{b}"
new_expression.append(term)
elif re.match(r'(\-?)\d+x', term):
print(term)
term = term.replace("x", "")
if term == "":
new_expression.append("x^2/2")
else:
new_expression.append(f"{int(term) / 2}x^2")
# Cases that can't be solved by the inverse power rule
elif term == "log x" or term == "log(x)":
new_expression.append("x(log(x)-1)")
elif term == "sin x" or term == "sin(x)":
new_expression.append("-cos(x)")
elif term == "e^x" or term == "e**x":
new_expression.append("e^x")
elif term == "1/x":
new_expression.append("log(x)")
elif term == "cos x" or term == "cos(x)":
new_expression.append("sin(x)")
elif term == "tan x" or term == "tan(x)":
new_expression.append("-log(cos((x))")
elif term == "sinh x" or term == "sinh(x)":
new_expression.append("cosh(x)")
elif term == "cosh x" or term == "cosh(x)":
new_expression.append("sinh(x)")
elif term == "tanh x" or term == "tanh(x)":
new_expression.append("log(cosh(x))")
elif term == "acos x" or term == "acos(x)":
new_expression.append("x*acos(x)-√(1-x^2)")
elif term == "asin x" or term == "asin(x)":
new_expression.append("√(1-x^2)+x*asin(x)")
elif term == "atan x" or term == "atan(x)":
new_expression.append("x*atan(x)-0.5*log(x^2+1)")
elif term == "acosh x" or term == "acosh(x)":
new_expression.append("x*asinh(x)-√(x^2+1)*√(x^2-1)")
elif term == "asinh x" or term == "asinh(x)":
new_expression.append("x*asinh(x)-√(x^2+1)")
elif term == "atanh x" or term == "atanh(x)":
new_expression.append("0.5*log(1-x^2)+x*atanh(x)")
elif term == "sec^2 x" or term == "sec^2(x)":
new_expression.append("tan(x)")
elif term == "sech^2 x" or term == "sech^2(x)":
new_expression.append("tanh(x)")
elif term == "-acos x" or term == "-acos(x)":
new_expression.append("√(1-x^2)-x*acos(x)")
elif term == "-log x" or term == "-log(x)":
new_expression.append("x-x*log(x)")
elif term == "-sin x" or term == "-sin(x)":
new_expression.append("cos(x)")
elif term == "-tan x" or term == "-tan(x)":
new_expression.append("log(cos(x))")
elif term == "-sinh x" or term == "-sinh(x)":
new_expression.append("-cosh(x)")
elif term == "-cosh x" or term == "-cosh(x)":
new_expression.append("-sinh(x)")
elif term == "-tanh x" or term == "-tanh(x)":
new_expression.append("-log(cos(x))")
elif term == "-asin(x)" or term == "-asin x":
new_expression.append("-√(1-x^2)-x*asin(x)")
elif term == "-atan x" or term == "-atan(x)":
new_expression.append("0.5*log(x^2+1)-x*atan(x)")
elif term == "-acosh x" or term == "-acosh(x)":
new_expression.append("√(x^2+1)*√(x^2-1)-x*acosh(x)")
elif term == "-asinh x" or term == "-asinh(x)":
new_expression.append("√(x^2+1)-x*asinh(x)")
elif term == "-atanh x" or term == "-atanh(x)":
new_expression.append("-0.5*log(1-x^2)-x*atanh(x)")
elif term == "-sec^2 x" or term == "-sec^2(x)":
new_expression.append("-tan(x)")
elif term == "-sech^2 x" or term == "-sech^2(x)":
new_expression.append("-tanh(x)")
elif term == "-e^x" or term == "-e**x":
new_expression.append("-e^x")
elif term == "-1/x":
new_expression.append("-log(x)")
elif term == "-cos x" or term == "-cos(x)":
new_expression.append("-sin(x)")
elif re.match(r'(\-?)\d+', term):
# Reverse slope
new_expression.append(term + "x")
# Combine all the terms into a single string
new_expression_str = ""
for term in new_expression:
if new_expression_str == "":
new_expression_str = term
else:
if term[0] == "-":
new_expression_str = new_expression_str + term
else:
new_expression_str = new_expression_str + "+" + term
ans = f"∫ ({og_expression}) dx = {new_expression_str} + C"
print(f"∫ ({og_expression}) dx = {new_expression_str} + C")
def scale_vector(scalar, vector):
global ans, ans_alt
ans = list(map(lambda x: x * scalar, vector))
return ans
def dot_product(vector1, vector2):
global ans, ans_alt
ans = sum([a * b for a, b in zip(vector1, vector2)])
return ans
def matrix_parse(matrix):
matrix = matrix.split(";")
matrixlist = []
def eval_(node):
if isinstance(node, ast.Constant): # <number>
return node.value
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
return operators[type(node.op)](eval_(node.left), eval_(node.right))
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
return operators[type(node.op)](eval_(node.operand))
else:
raise TypeError(node)
for row in matrix:
if row[0] == "[":
row = row[1:]
if row[len(row) - 1] == "]":
row = row[:len(row) - 1]
row = "[" + row + "]"
row = list(
map(lambda x: eval_(ast.parse(x, mode='eval').body),
row.strip('][').split(', ')))
# row = list(map(lambda x: complex(x) if "j" in x else int(x), row))
matrixlist.append(row)
return matrixlist
def verify_square(input_matrix):
rows = len(input_matrix)
first_row_len = len(input_matrix[0])
if first_row_len != rows:
return False
else:
for row in input_matrix:
if len(row) != first_row_len:
return False
else:
continue
return True
def format_mat(mat):
string = "["
for i in mat:
for j in i:
string += f"{j}, "
string = string[:len(string) - 2]
string += ";"
string = string[:len(string) - 1]
return f"[{string}]"
def transpose(matrix):
global ans, ans_alt
new_matrix = []
for col in range(len(matrix[0])):
new_matrix.append([])
for i in range(len(new_matrix)):
for row in matrix:
new_matrix[i].append(row[i])
ans = format_mat(new_matrix)
return new_matrix
def fft(x):
global ans, ans_alt
N = len(x)
if N == 1:
return [x[0]]
transformed_x = [0] * N
even = fft(x[:N:2])
odd = fft(x[1:N:2])
for k in range(N // 2):
w = cmath.exp(-2j * math.pi * k / N)
transformed_x[k] = even[k] + w * odd[k]
transformed_x[k + N // 2] = even[k] - w * odd[k]
ans = transformed_x
return transformed_x
def ifft(x):
global ans, ans_alt
N = len(x)
if N == 1:
return [x[0]]
transformed_x = [0] * N
even = ifft(x[:N:2])
odd = ifft(x[1:N:2])
for k in range(N // 2):
w = cmath.exp(2j * math.pi * k / N)
transformed_x[k] = (even[k] + w * odd[k]) / N
transformed_x[k + N // 2] = (even[k] - w * odd[k]) / N
ans = transformed_x
return transformed_x
def pretty_print_matrix(matrix):
if type(matrix) != list:
matrix = matrix[0].tolist()
for i in range(len(matrix)):
if i == 0:
print(f"[ {str(matrix[0]).replace('[', '').replace(']', '')}")
elif i == len(matrix) - 1:
print(f" {str(matrix[i]).replace('[', '').replace(']', '')} ]")
else:
print(f" {str(matrix[i]).replace('[', '').replace(']', '')}")
def conjugate(num):
global ans, ans_alt
new_matrix = [[x.conjugate() if type(x) == complex else x for x in row]
for row in matrix]
ans = format_mat(new_matrix)
return new_matrix
def eval_(node):
if isinstance(node, ast.Constant): # <number>
return node.value
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
return operators[type(node.op)](eval_(node.left), eval_(node.right))
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
return operators[type(node.op)](eval_(node.operand))
else:
raise TypeError(node)
def matrix_multiplication(A, B):
global ans, ans_alt
# Check if the matrices can be multiplied
if len(A[0]) != len(B):
raise ValueError("Matrix dimensions are not compatible for multiplication")
result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
ans = format_mat(result)
return result
def calc_angle(a, b, c):
#Calculate the m∠ABC
# https://muthu.co/using-the-law-of-cosines-and-vector-dot-product-formula-to-find-the-angle-between-three-points/
numerator = (a[0]-b[0])**2 + (a[1]-b[1])**2 + ((b[0]-c[0])**2+(b[1]-c[1])**2) - ((a[0]-c[0])**2+(a[1]-c[1])**2)
denominator = 2*(math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)*math.sqrt((b[0]-c[0])**2+(b[1]-c[1])**2))
return math.acos(numerator/denominator)*57.296
ascii_art = """ ______ __ __
/ \ / | / |
/$$$$$$ | ______ ____$$ | ______ ______ ______ $$ |____ ______ ______
$$ | $$/ / \ / $$ | / \ / \ / \ $$ \ / \ / \
$$ | /$$$$$$ |/$$$$$$$ |/$$$$$$ |/$$$$$$ |/$$$$$$ |$$$$$$$ |/$$$$$$ |$$$$$$ |
$$ | __ $$ | $$ |$$ | $$ |$$ $$ |$$ | $$ |$$ $$ |$$ | $$ |$$ | $$/ / $$ |
$$ \__/ |$$ \__$$ |$$ \__$$ |$$$$$$$$/ $$ \__$$ |$$$$$$$$/ $$ |__$$ |$$ | /$$$$$$$ |
$$ $$/ $$ $$/ $$ $$ |$$ |$$ $$ |$$ |$$ $$/ $$ | $$ $$ |
$$$$$$/ $$$$$$/ $$$$$$$/ $$$$$$$/ $$$$$$$ | $$$$$$$/ $$$$$$$/ $$/ $$$$$$$/
/ \__$$ |
$$ $$/
$$$$$$/ """
print(ascii_art)
print("Created in 2023 by Samir R")
while True:
cmd = input("COMMAND>")
cmd = cmd.upper()
if cmd == "SOLVE":
equation = input("EQUATION TO BE SOLVED>")
solve(equation)
elif cmd == "":
continue
elif cmd == "DIFF":
equation = input("EXPRESSION TO BE DIFFERENTIATED>")
derivative(equation)
elif cmd == "SCALE":
vector = input("VECTOR>")
vector = list(map(float, vector.strip('][').split(', ')))
scalar = float(input("SCALAR>"))
ans = str([round(float(i), eps) for i in scale_vector(scalar, vector)])
print(ans)
elif cmd == "DOTPR":
vectorA = input("VECTOR A>")
vectorA = list(map(float, vectorA.strip('][').split(', ')))
vectorB = input("VECTOR B>")
vectorB = list(map(float, vectorB.strip('][').split(', ')))
ans = round(dot_product(vectorA, vectorB), eps)
print(ans)
elif cmd == "ADDVEC":
vectorA = input("VECTOR A>")
vectorA = list(map(float, vectorA.strip('][').split(', ')))
vectorB = input("VECTOR B>")
vectorB = list(map(float, vectorB.strip('][').split(', ')))
ans = str([round(i, eps) for i in blas.saxpy(vectorA, vectorB)])
print(ans)
elif cmd == "EIGVAL":
matrix = input("Matrix>")
matrix = matrix_parse(matrix)
eigenvalues = lapack.sgeev(matrix)
print(type(eigenvalues[0]))
ans = str([round(i, eps) for i in eigenvalues[0]])
print("EIGENVALUES:")
for eigenvalue in eigenvalues[0]:
print(round(eigenvalue, eps))
elif cmd == "T":
matrix = input("Matrix>")
matrix = matrix_parse(matrix)
matrix = transpose(matrix)
ans = format_mat(matrix)
pretty_print_matrix(matrix)
elif cmd == "FFT":
signal = input("SIGNAL(AS VECTOR)>")
signal = list(map(int, signal.strip('][').split(', ')))
ans = fft(signal)
print(ans)
elif cmd == "IFFT":
signal = input("SIGNAL(AS VECTOR)>")
signal = list(map(complex, signal.strip('][').split(', ')))
ans = ifft(signal)
print(ans)
elif cmd == "INTEGRATE":
expression = input("EXPRESSION TO INTEGRATE>")
integrate(expression)
elif cmd == "SUM":
vector = input("VECTOR>")
vector = list(map(int, vector.strip('][').split(', ')))
ans = round(sum(vector), eps)
print(ans)
elif cmd == "AVG":
vector = input("VECTOR>")
vector = list(map(int, vector.strip('][').split(', ')))
ans = round(sum(vector) / len(vector), eps)
print(ans)
elif cmd == "WORD":
word = input_prim("WORD>")
df = pd.read_csv('english Dictionary.csv')
rows = df.loc[df['word'] == word]
print(f"DEFINITION OF {word}")
i = 1
for row in rows["def"]:
print(row)
i += 1
print(f"{i}. - {row}")
elif cmd == "EXP":
expression = input("EXPONENT>")
if "[" in expression and not ";" in expression:
expression = expression.strip('][').split(', ')
ans = str([
round(cmath.exp(eval_(ast.parse(i, mode='eval').body)), eps) for i in expression
])
print(ans)
elif "[" in expression and ";" in expression:
expression = matrix_parse(expression)
ans = format_mat([[round(cmath.exp(i), eps) for i in j] for j in expression])
pretty_print_matrix([[round(cmath.exp(i), eps) for i in j] for j in expression])
else:
ans = round(cmath.exp(eval_(ast.parse(expression, mode='eval').body)), eps)
print(ans)
elif cmd == "SQRT":
expression = input("INPUT>")
if "[" in expression and not ";" in expression:
expression = expression.strip('][').split(', ')
ans = str([
round(cmath.sqrt(eval_(ast.parse(i, mode='eval').body)), eps) for i in expression
])
print(ans)
elif "[" in expression and ";" in expression:
expression = matrix_parse(expression)
ans = format_mat([[round(cmath.sqrt(i), eps) for i in j] for j in expression])
pretty_print_matrix([[round(cmath.sqrt(i), eps) for i in j] for j in expression])
else:
ans = round(cmath.sqrt(eval_(ast.parse(expression, mode='eval').body)), eps)
print(ans)
elif cmd == "SIN":
expression = input("INPUT>")
if "[" in expression and not ";" in expression:
expression = expression.strip('][').split(', ')
ans = [
round(cmath.sin(eval_(ast.parse(i, mode='eval').body)), eps) for i in expression
]
print(ans)
elif "[" in expression and ";" in expression:
expression = matrix_parse(expression)
ans = format_mat([[round(cmath.sin(i), eps) for i in j] for j in expression])
pretty_print_matrix([[round(cmath.sin(i), eps) for i in j] for j in expression])
else:
ans = round(cmath.sin(eval_(ast.parse(expression, mode='eval').body)), eps)
print(ans)
elif cmd == "COS":
expression = input("INPUT>")
if "[" in expression and not ";" in expression:
expression = expression.strip('][').split(', ')
ans = [
round(cmath.cos(eval_(ast.parse(i, mode='eval').body)), eps) for i in expression
]
print(ans)
elif "[" in expression and ";" in expression:
expression = matrix_parse(expression)
ans = format_mat([[round(cmath.cos(i), eps) for i in j] for j in expression])
pretty_print_matrix([[round(cmath.cos(i), eps) for i in j] for j in expression])
else: