-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmathExampleLibrary.py
More file actions
74 lines (61 loc) · 2.3 KB
/
Copy pathmathExampleLibrary.py
File metadata and controls
74 lines (61 loc) · 2.3 KB
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
# Common Math Functions for Algebra & Precalc
# Requires: pip install sympy matplotlib
# Disclaimer use this as a way to check your work or practice
# math. Do NOT use for cheating, homework, etc. Always
# check your work. There is no gurantee these functions are
# correct, check your work.
import sympy as sp
import matplotlib.pyplot as plt
import numpy as np
# Define a common symbol
x = sp.symbols('x')
# ---------------- Algebra Basics ----------------
def simplify_expr(expr):
"""Simplify an algebraic expression"""
return sp.simplify(expr)
def expand_expr(expr):
"""Expand an algebraic expression"""
return sp.expand(expr)
def factor_expr(expr):
"""Factor an algebraic expression"""
return sp.factor(expr)
def solve_equation(expr, variable=x):
"""Solve equation expr = 0 for variable"""
return sp.solve(expr, variable)
# ---------------- Precalc Functions ----------------
def derivative(expr, variable=x):
"""Find derivative of expression"""
return sp.diff(expr, variable)
def integral(expr, variable=x):
"""Find indefinite integral of expression"""
return sp.integrate(expr, variable)
def definite_integral(expr, a, b, variable=x):
"""Find definite integral from a to b"""
return sp.integrate(expr, (variable, a, b))
def limit(expr, point, variable=x):
"""Find the limit of an expression as variable -> point"""
return sp.limit(expr, variable, point)
# ---------------- Graphing ----------------
def plot_function(expr, xmin=-10, xmax=10):
"""Graph a function using matplotlib"""
f = sp.lambdify(x, expr, 'numpy')
xs = np.linspace(xmin, xmax, 400)
ys = f(xs)
plt.plot(xs, ys, label=str(expr))
plt.axhline(0, color='black', lw=0.5)
plt.axvline(0, color='black', lw=0.5)
plt.legend()
plt.grid(True)
plt.show()
# ---------------- Examples ----------------
if __name__ == "__main__":
expr = x**2 - 5*x + 6
print("Simplify:", simplify_expr((x**2 + 2*x + 1)/(x+1)))
print("Expand:", expand_expr((x-2)*(x+3)))
print("Factor:", factor_expr(expr))
print("Solve:", solve_equation(expr))
print("Derivative:", derivative(sp.sin(x)))
print("Integral:", integral(sp.cos(x)))
print("Definite Integral:", definite_integral(x**2, 0, 3))
print("Limit:", limit(sp.sin(x)/x, 0))
plot_function(expr)