Python 2
Python 2
Faculty of Information
Technology
1. Sympy
SymPy is a Python library for symbolic mathematics. It aims to become a full-
featured computer algebra system (CAS) while keeping the code as simple as
possible in order to be comprehensible and easily extensible.
1.1 Setup:
If you have Python and PIP already installed on a system, then install it using
this command:
python -m pip install sympy
1.2 Introduction
Symbolic computation systems such as SymPy are capable of computing
symbolic expressions with variables. Let us define a symbolic expression,
representing the mathematical expression x+2y.
Note that we wrote x +2∗y just as we would if x and y were ordinary Python
variables. But in this case, instead of evaluating to something, the expression
remains as just x +2∗y . Now let us play around with it:
https://docs.sympy.org/latest/tutorials/intro-tutorial/intro.html
1.3 Practice examples:
Solve x 2+ 4 x + 4=0.
import sympy as sp
Trinh Hung Cuong - Applied Calculus for IT - 501031 1/5
Ton Duc Thang University
Faculty of Information
Technology
x = sp.symbols('x')
root = sp.solve(x**2 + 4*x + 4)
print(root)
Plot functions:
import sympy as sp
import math
x = sp.symbols('x')
f5a = abs(x)**(1/2)
sp.plot(f5a, (x, -10, 10), line_color='red') #tuple
f5d = math.e**x
sp.plot(f5d, (x, -10, 10), line_color='blue')
f5e = sp.log(x)
sp.plot(f5e, (x, -10, 10))
x = sp.symbols('x')
f = x*x - x + 1
Exercise 0
Write a Python program to plot the following functions on a graph, and mark the intersection point of
f1 and f2:
Hint:
import sympy as sp
import matplotlib.pyplot as plt
import numpy as np
y1 = ...
y2 = ...
plt.plot(x, y1)
plt.plot(x, y2)
x_root = sp.solve(...)
y_root = f1.subs(...) #f1(x_root[0]) = f1(2)
#infinity: sp.oo
#factorial: sp.factorial(...)
Right/Left limit:
import sympy as sp
import math
#3.1
x = sp.symbols('x')
f3_1 = 1/( 1 + 2**(1/x) )
lmRight = sp.limit(f3_1, x, 0, '+')
print ("Right limit = " , lmRight )
lmLeft = sp.limit(f3_1, x, 0, '-')
print ("Left limit = " , lmLeft )
Continuity
Ex6:
import numpy as np
import sympy as sp
x = sp.symbols('x')
f6a = ...
#At point x = 0
lm_x_0 = sp.limit(f6a, x, 0)
#Compare lm_x_0 and f(0)
...
#Other points x != 0
for c in np.arange(-100, 100, 1):
if c != 0:
lm_x_c = sp.limit(f6a, x, c)
#Compare lm_x_c and f(c)
Homework:
Exercises 8 in the PDF file “Lab04.ex.pdf”
2. References
- Python Tutorial on the W3schools website:
https://www.w3schools.com/python/default.asp
- Python Tutorial on the Tutorials Point website:
https://www.tutorialspoint.com/python/index.htm
-- THE END --