You are on page 1of 27

MATH102 Recitation Manual for Python

Department of Mathematics

Dr. Waled Al-Khulaifi


Dr. Ibrahim Sarumi
Dr. Slim Belhaiza
Dr. Abdulelah Qadiri
January 21, 2023

1
Contents
1 Introduction 4
1.1 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.2 Storing Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Exponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Basic Mathematical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5 Mathematical Variables and Functions . . . . . . . . . . . . . . . . . . . . . . 7
1.6 Plotting Functions/Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2 Areas and Distances 12

3 The Fundamental Theorem of Calculus 25

4 Indefinite Integrals and the Net Change Theorem 28

5 Average Value of a Function 33

6 The Substitution Rule 36

7 The Natural Logarithmic, Inverse Trigonometric and Hyperbolic Functions: In-


tegration 39

8 Areas between two curves 40

9 Volumes (Disks and Washers) 50

10 Volumes by cylinderical shells 57

11 Length of an arc 61

12 Area of a surface of revolution 66

13 Integration by parts 68

14 Trigonometric Integrals 72

15 Trigonometric Substitution 76

16 Integration of Rational Functions by Partial Fractions 80

17 Strategy for Integration 82

18 Improper Integrals 83

19 Sequences 85

20 Infinite Series 87

2
21 The integral Test 89

22 Comparison Tests 91

23 Alternating Series 93

24 Absolute Convergence and the Ratio and Root Tests 94

25 Strategy for Testing Series 96

26 Power Series 97

27 Taylor and Maclaurin Series 99

3
1 Introduction
Python became the trend in scientific community due to its efficient programming algo-
rithms. It has been proving to be powerful in machine learning, deep learning, artificial
intelligence, . . . etc. In this manual, we introduce the mathematical packages to help in
tackling problems related to Calculus such as integration, sequences, series, Taylor and
Maclaurin Series.

1.1 Arithmetic Operations


Symbol Operation Example
+ Addition 2+3
- Subtraction 2-3
* Multiplication 2*3
/ Division 2/3
Some examples of using Python as a calculator are given below
[1]: 2*(5+4)

[1]: 18

[2]: 4/2 + 3

[2]: 5.0

[3]: 5 + 13 /2

[3]: 11.5

[4]: (5 + 13)/2 # It is always better to use parentheses ()

[4]: 9.0

1.2 Storing Values


[5]: a = 33*7 # a is stored in the memory
b = 11/3

a #to display a

[5]: 231

[6]: b #to display b

4
[6]: 3.6666666666666665

Notice that Python shows the outcome of the last variable only, to show them all use the
command display() or print()
[9]: display(a,b)

231

3.6666666666666665

[10]: print(a,b)

231 3.6666666666666665
[11]: print("a = ", a)

a = 231
[12]: print('b = ', b)

b = 3.6666666666666665

1.3 Exponent
We use ** to calculate the exponents for example, if we want to calculate 23 we type 2**3.
[13]: 2**(3)

[13]: 8

[14]: 2**(0.5)

[14]: 1.4142135623730951

[15]: sqrt(2)


,! ---------------------------------------------------------------------------

NameError Traceback (most recent�


,! call last)

<ipython-input-15-5693fe9b0a8a> in <module>
----> sqrt(2)

5
NameError: name 'sqrt' is not defined

Here Python is not like MATLAB, it is more like an environment or platform where we
can recall libraries (packages) for specific purposes of calculation and processing.

1.4 Basic Mathematical Functions


In order to call the known mathematical functions, such as sin x, cos x, ln x, e x , we need
to import the necessary libraries. Without these libraries, Python will not compile com-
plicated mathematical expression like sqrt(2) as shown above.
In this manual we consider the two libraries for mathematical computations:
• Sympy : For symbolic calculations
• Numpy : For numerical calculations
We use the command pair import and as to call any needed library.
[17]: import sympy as smp #Here 'as' means that we type 'smp' whenever we�
,!want to recall this library

import numpy as np #Here 'as' means that we type 'np' whenever we want�
,!to recall this library

Now whenever we want to use a function, we include smp. or np. in it. For example
smp.sqrt(5) or np.sqrt(5)
[18]: smp.sqrt(5)
p
[18]: 5

[19]: np.sqrt(5)

[19]: 2.23606797749979
p
Notice that when we asked for 5 through Sympy it returns the symbolic output of it
while Numpy gave its numerical value.
[20]: smp.log(4)

[20]: log (4)

[21]: np.log(4)

[21]: 1.3862943611198906

for simplicity we can use the following the command to call everything from sympy or
numpy.

6
Be warned that by using this for two libraries together will cause the later library to over-
ride the former one.
[22]: from numpy import *
from sympy import *

[23]: sin(4)

[23]: sin (4)

The line of codes below shows how we call the number p from different libraries keeping
in mind that we set the default library to be sympy.
[24]: v_1 = smp.pi #the number pi in Sympy
v_2 = np.pi #the number pi in numpy
v_3 = pi # if import * is used, notice the one imported as *�
,!is sympy

display(v_1, v_2,v_3)

sin(v_3)

p
3.141592653589793

p
[24]: 0

1.5 Mathematical Variables and Functions


To define a variable in Python, for example x, we use the following command
x= smp.Symbol('x')
or if we used import * then simply we type
x=Symbol('x')
[25]: #You have to define the variables before defining the function(s)
x = smp.Symbol('x')
display(x)

x
[26]: smp.sin(x)

[26]: sin ( x )

7
The table below gives the syntax for the most used mathematical functions in sympy.
Mathematical Expression Sympy Mathematical Expression Sympy
sin( x ) sin(x) 1
cot ( x ) acot(x)
cos( x ) cos(x) 1
sec ( x ) asec(x)
tan( x ) tan(x) 1
csc ( x ) acsc(x)
cot( x ) cot(x) ex exp(x)
sec( x ) sec(x) ln( x ) ln(x)
csc( x ) csc(x) logy ( x ) log(x,y)
1 n
sin ( x ) asin(x) x x**n
1
p
cos ( x ) acos(x) x sqrt(x)
1
p
tan ( x ) atan(x) n
x root(x,n)
If we want to define an unknown function then we simply use Function from sympy
[27]: t = smp.Symbol('t')
f=smp.Function('f')(x)
display(f)

f=smp.Function("f")(x,t) ##x here was defined in previous cell


display(f)
print(f)

f (x)
f ( x, t)
f(x, t)
Now let us define a function explicitly in terms of know functions
[28]: h = smp.sin(x) + x + smp.exp(x)
display(h)

x + e x + sin ( x )
Let us try to find the value of h when x = p
[29]: h(smp.pi)


,! ---------------------------------------------------------------------------

TypeError Traceback (most recent�


,! call last)

8
<ipython-input-29-5317fc83087a> in <module>
----> 1 h(smp.pi)

TypeError: 'Add' object is not callable

Using the previous definition of function, we can not substitute as h(x). We have two
ways to do the substitution:
(1) We define the function using .subs( , ) as follow
[30]: h.subs(x,smp.pi)

[30]: p + ep
(2) We define the function using lamba as follow
[31]: q = lambda x: smp.sin(x) + smp.exp(x)
display(q) # Gives the type of q, which is a function
display(q(x)) # Display the function
print("q(x) = ", q(x))

<function __main__.<lambda>(x)>

e x + sin ( x )
q(x) = exp(x) + sin(x)
Then we can substitute like we do in MATLAB
[32]: q(5)

[32]: sin (5) + e5

To get the numerical value of q(5) (or any numerical presented as symbolic expression)
we use the command float to transform it into decimal form
[33]: float(q(5))

[33]: 147.45423482791347

9
1.6 Plotting Functions/Equations
There are many libraries that can be used for plotting for example, sympy and matplotlib.
In sympy we use the command plot for plotting functions of single variable.
[36]: smp.plot(x**(0.5))

We can plot equations using plot_implicit but first we have to define the variables that
are involved in the equation
[1]: from sympy import *
x,y = symbols("x y", real=True)

Notice that we set the variables to be real numbers by adding real = True
[2]: plot_implicit(x**2 + y**2 -4)

10
Exercise
(1) Write a python code to print the function

f ( x ) = x2 + 5, x 2 R

(2) Find the value of f at x = 1.3 then print it as (the value = . . . ).


(3) Plot the function f .

11
2 Areas and Distances
Example 1
1
(a) Estimate the area under the graph of the function f ( x ) = x 2 +1
from x = 0 to x = 4
using n = 3 approximating rectangles and
1. right-end points
2. left-end points
3. midpoints.
(b) Graph the function curve and the estimating rectangles.
(c) Increase the number of approximating recatngles to n = 40.

Solution
(a) First we import the needed packages and libraries
[1]: import sympy as smp # This package is for symbolic mathematics
import numpy as np # This package for creating arrays (i.e. Matrices)
import matplotlib.pyplot as plt # This is for plotting

Next we declare the variables and the function, for example we set a = 0, b = 4 and
n = 3.
[2]: x=smp.symbols('x', real=True)
f = lambda x: 1/(1+x**2) # The Lambda keyword is to define f as a�
,!function of x

a=0; b=4; n=3

You can display the entered data and the output by using the command display() or
print(). It is a good way to understand how the program treats and process the data.
[3]: display(f(x))
display(a)
display(b)
display(n)

1
x2 +1
0

12
We define the line space for x and then the line space for the values of the function f at
each x.
[4]: xvalues = np.linspace(a, b, n+1)
yvalues = f(xvalues) #You can check the sample points�
,!by using display(xvalues)

Now we evaluate the width of subinterval, midpoints and then the Riemann sums.
[5]: deltax = (b-a)/n # The equal width of the each subinterval

midpoints= (xvalues[1:]+xvalues[:-1])/2 # Array of midpoints


display(midpoints) # To display the midpoints

yvalues_M = f(midpoints) # The values of the function on midpoints

Re_L = (np.sum(yvalues[:-1])) * deltax # Reimann Sum when the samples are�


,!the

# left-end points
Re_R = (np.sum(yvalues[1:])) * deltax # Reimann Sum when the samples are�
,!the

# right-end points
Re_M = (np.sum(yvalues_M)) * deltax # Reimann Sum when the samples are�
,!the

# midpoints
print("Approximating area using left-end points is ", Re_L)
print("Approximating area using right-end points is ", Re_R)
print("Approximating area using midpoints is ", Re_M)

array([0.66666667, 2. , 3.33333333])

Approximating area using left-end points is 1.9777168949771688


Approximating area using right-end points is 0.7228149341928551
Approximating area using midpoints is 1.2998353328628558
(b) Now lets try to plot the function first evaluated at the left-end points.
[6]: fig = plt.figure(figsize = (8, 8)) #This command is for determining the�
,!size of the figure

plt.plot(xvalues,yvalues,'r')

[6]: [<matplotlib.lines.Line2D at 0x181c33c3248>]

13
As we see in the figure that the curve of the function is not smooth enough as we know.
Thus, we need to expand the linespace for x values.
[7]: Xmorevalues = np.linspace(a,b,n*n+100) # We increased the line space to�
,!n*n+100

# You can change it to any large�


,!value
ymorevalues = f(Xmorevalues)

Now we try to plot the function using the above line spaces
[8]: fig = plt.figure(figsize = (8, 8))
plt.plot(Xmorevalues,ymorevalues,'r')

14
[8]: [<matplotlib.lines.Line2D at 0x181c45b3208>]

We add the plot of the approximating rectangles to the graph of f .


[9]: fig = plt.figure(figsize = (8, 8))
plt.plot(Xmorevalues,ymorevalues,'r')
plt.plot(xvalues, yvalues, 'm.', markersize=15)
x_left = xvalues[:-1]
y_left = yvalues[:-1]
plt.bar(x_left, y_left, width= deltax, alpha=0.75 , align='edge',�
,!edgecolor='b')

plt.title('Approximating Rectangles Using Left-End Points')

15
[9]: Text(0.5, 1.0, 'Approximating Rectangles Using Left-End Points')

[10]: fig = plt.figure(figsize = (8, 8))


plt.plot(Xmorevalues,ymorevalues,'r')
plt.plot(xvalues, yvalues, 'm.', markersize=15)
x_right = xvalues[1:]
y_right = yvalues[1:]
plt.bar(x_right, y_right, width= -deltax, alpha=0.75 , align='edge',�
,!edgecolor='b')

plt.title('Approximating Rectangles Using Right-End Points')

[10]: Text(0.5, 1.0, 'Approximating Rectangles Using Right-End Points')

16
[11]: fig = plt.figure(figsize = (8, 8))
plt.plot(Xmorevalues,ymorevalues,'r')
plt.plot(midpoints, yvalues_M, 'm.', markersize=15)
x_mid = midpoints
y_mid = yvalues_M
plt.bar(midpoints, yvalues_M, width= deltax, alpha=0.75 , align='center',�
,!edgecolor='b')

plt.title('Approximating Rectangles Using MidPoints')

[11]: Text(0.5, 1.0, 'Approximating Rectangles Using MidPoints')

17
(c) We repeat the above codes except when n = 100.
[12]: x=smp.symbols('x', real=True)
f = lambda x: 1/(1+x**2) # The Lambda keyword is to define f as a�
,!function of x

# and to be able to evaluate it over an array


a=0; b=4; n=40
xvalues = np.linspace(a, b, n+1)
yvalues = f(xvalues)

deltax = (b-a)/n # The equal width of the each subinterval

18
midpoints= (xvalues[1:]+xvalues[:-1])/2 # Array of midpoints

yvalues_M = f(midpoints) # The values of the function on midpoints

Re_L = (np.sum(yvalues[:-1])) * deltax #Reimann Sum when the samples are�


,!the

# left-end points
Re_R = (np.sum(yvalues[1:])) * deltax #Reimann Sum when the samples are�
,!the

# right-end points
Re_M = (np.sum(yvalues_M)) * deltax #Reimann Sum when the samples are�
,!the

# midpoints
print("Approximating area using left-end points is ", Re_L)
print("Approximating area using right-end points is ", Re_R)
print("Approximating area using midpoints is ", Re_M)
Xmorevalues = np.linspace(a,b,n*n+100) # We increased the line space to�
,!n*n+100

# You can change it to any big�


,!enough value

# Notice that we name it with�


,!upper case X.

plt.figure(1)
fig = plt.figure(figsize = (8, 8))
ymorevalues = f(Xmorevalues)
plt.plot(Xmorevalues,ymorevalues,'r')
plt.plot(xvalues, yvalues, 'm.', markersize=15)
x_left = xvalues[:-1]
y_left = yvalues[:-1]
plt.bar(x_left, y_left, width= deltax, alpha=0.75 , align='edge',�
,!edgecolor='b')

plt.title('Approximating Rectangles Using Left-End Points')

plt.figure(2)
fig = plt.figure(figsize = (8, 8))
plt.plot(Xmorevalues,ymorevalues,'r')
plt.plot(xvalues, yvalues, 'm.', markersize=15)
x_right = xvalues[1:]
y_right = yvalues[1:]
plt.bar(x_right, y_right, width= -deltax, alpha=0.75 , align='edge',�
,!edgecolor='b')

plt.title('Approximating Rectangles Using Right-End Points')

19
plt.figure(3)
fig = plt.figure(figsize = (8, 8))
plt.plot(Xmorevalues,ymorevalues,'r')
plt.plot(midpoints, yvalues_M, 'm.', markersize=15)
x_mid = midpoints
y_mid = yvalues_M
plt.bar(midpoints, yvalues_M, width= deltax, alpha=0.75 , align='center',�
,!edgecolor='b')

plt.title('Approximating Rectangles Using MidPoints')

Approximating area using left-end points is 1.3728534215404986


Approximating area using right-end points is 1.2787357744816754
Approximating area using midpoints is 1.3258291955989039
[12]: Text(0.5, 1.0, 'Approximating Rectangles Using MidPoints')

<Figure size 432x288 with 0 Axes>

20
21
22
Exercise 1
p
Consider the function f ( x ) = 1 + 2x.
Write a program that calculates the approximating area of the region under the curve of f
where the user enters the interval endpoints a and b and the desired number of recatngles
using left-end points.
Hint You may need to use the following commands:
• input() (important to use)
• float()
• int()

23
Exercise 2
Solve Ex.31, Ex.34, Ex.67 and Ex.68 in Section 5.2.

24
3 The Fundamental Theorem of Calculus
Example 1
Evaluate the integral.
R4
(a) 0 ( x5 3x + 9) dx
R p/3
(b) 0 (sec2 ( x ) + sin( x )) dx
R 6 q5
(c) 1 x dx
R4
(d) 1 f ( x ) dx where
8
<6
> 0x<2
f (x) =
>
:
9 x3 2  x  4.

Solution
(a) We use the command integrate from sympy as follow
[13]: import sympy as smp # This package is for symbolic mathematics
x = smp.Symbol('x') # Set x as a variable
f = smp.Function('f')(x) # define f as a function of x

f = x**5 -3*x +9 # The expression of f

display(f) # To check whether is the correct�


,!expression of f

smp.integrate(f,(x,0,4)) # We integrate f over the given interval

x5 3x + 9
2084
3
We repeat the same steps as above but with changing the function name. For part (b) we
have
[14]: g = smp.Function('g')(x)
g = smp.sec(x)**2 + smp.sin(x) #smp.sec for secant and smp.sin for sine

display(g)

smp.integrate(g, (x,0,smp.pi/3)) # smp.pi is to call pi

25
sin ( x ) + sec2 ( x )
1 p
+ 3
2
Part (c)
[15]: g1 = smp.Function('g1')(x)
g1 = smp.sqrt(5/x) #smp.sqrt is to call the square root

display(g1)

smp.integrate(g1, (x,1,6))
r
p 1
5
x
p p
2 5 + 2 30
For part (d) we need to define a piece-wise funciton.
[16]: g2 = smp.Function('g2')(x)
g2 = smp.Piecewise((6, (0<= x) &(x<2)), (9 - x**3 , (2<= x) & (x <= 4)))

# In the above syntax, we use & for expressing the condition 0<= x< 2 as�
,!combined

# conditions of 0<= x and x<2. Thats because smp.Piecwise does not�


,!support chained

# inequalities.

display(g2)

smp.integrate(g2, (x,1,4))
(
6 for x 0 ^ x < 2
3
9 x for x 2 ^ x  4
36

Exercise 1
Solve Ex.7, Ex.14, Ex.21, Ex.28 and Ex.41 in Section 5.4. (Hint: You may need to use the
command Abs() for defining the absolute value of an expression)

26
Example 2
Find the derivative of the function
Z x2
F(x) = ln(4 + t) dt.
1 2x

Solution
[17]: t = smp.Symbol('t')
f1 = smp.Function('f1')(x)

f1 = smp.integrate(smp.ln(4+t), (t, 1-2*x, x**2)) # we define the�


,!function as an integral

f11 = smp.diff(f1,x) # This command for taking the derivative

smp.simplify(f11) # We need to simplify the result


⇣ ⌘
2
2x log x + 4 + 2 log (5 2x )

Notice that the answer expressed in terms log instead of ln because Python considers it
as the natural logarithm.

Exercise 2
Solve Ex.75, Ex.79, Ex.83 and Ex.86 in Section 5.4.
(Hint: You may need to use the command ‘smp.diff(function, variable, n)where n stands
for the order of the derivative.

27

You might also like