0% found this document useful (0 votes)
4 views

maths_practical1

Uploaded by

patilanuj49
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

maths_practical1

Uploaded by

patilanuj49
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Mathematics Lab-03

MTC-243 : Mathematics Practicals


Python Programming

Name :-
Roll No. :-
Std. :- SY.BSC (Computer Science)
College :- RNC Arts, JDB Com and NSC Sci and Comp Sci college, Nashik road
Sub. Teacher :- Miss.Apurva Joshi and Mrs.Priti Mojad
Sr.No. Title Remark
01. Graph Plotting – I (2D)
02. Graph Plotting – II (2D)
03. Graph Plotting – I (3D)
04. Graph Plotting – II (3D)
05. Application To Computational Geometry
06. Computational Geometry – Points And Lines
07. Polygon, 2D and 3D Rotation and Reflection
08. Generation of Bezier Curve
09. Linear Programming in Python
10. Transportation Problem

This is to certify that Mr/Ms _________________________ of class S.Y.BSC (Computer Science) Seat no.
__________ has completed __ /10 experiments in Mathematics in academic year 2022-23.
Date :- ___ /___ /______

Practical Incharge Nilesh B. Mahajan


HOD, Dept. of Comp Sci.

External Examiner Internal Examiner

1
Practical No.01 :- Graph Plotting – I(2D)
# Installation of Numpy and Matplotlib Packege :-
• Linux :- >>> python -m pip install -U pip setuptools
• Windows :- >>> python -m pip install matplotlib
# 2D Plots :-
• We can import all function from pylab, Pylab combines pyplot with numpy
into a single namespace. We can import via :-
>>> from pylab import
>>> import matplotlib.pyplot as plt
>>> import numpy as np
• plot() :- We use this function to plot the graphs.
• show() :- We use this function to display the graphs.
Example. If there are two vectors x ,y then

>>> plot(x, y)
>>> show()

Que.) Plot the graphs for the following points :-


A(1, 1), B(2, 4), C(3, 9), D(4, 16), E(5,25).

Sol. :- >>> from pylab import*

>>> import matplotlib.pyplot as plt

>>> import numpy as np

>>> x = [1, 2, 3, 4, 5]

>>> y = [1, 4, 9, 16, 25]

>>> plot(x, y)

>>> Show()

2
# Functions Of Numpy Module :-
➢ np.arrange() :- (start, end, step)
- It returns evenly spaced value with given step within interval [start, end].
Example. >>> from pylab import* Example. >>> np.arrange(0, 100, 0.1)
>>> import numpy as np Sol. :- [0, 0.1, 0.2, 0.3 ,…, 99.8, 99.9]
>>> np.arrange(0, 1, 0.2)
Sol. :- [0, 0.2, 0.4, 0.6, 0.8]

➢ np.linspace() :- (start, end, subintervals)


- It returns spaced number over a specified interval [start, end) in given number of subintervals.
Example.>>> from pylab import* Example. >>> np.linspace(0, 1, 100)
>>> import numpy as np Sol. :- array([0. , 0.01, 0.02, …. , 0.97, 0.98, 0.99, 1. ])
>>> np.linspace(0,1,5)
Sol. :- array([0. , 0.25, 0.5, 0.75, 1. ])
➢ np.sin(x), np.exp(x), etc. :- We use this Functions for Trigonometric Functions.
Que.) Plot the graphs for the following :-

1) f(x) = x^2 in [0, 5] 2) f(x) = x^3 in [-5, 5]

Sol. :->>> from pylab import* Sol. :- >>> from pylab import*

>>> import numpy as np >>> import numpy as np

>>> x = np.linspace(0, 5, 10) >>> x = np.linspace(-5, 5, 10)

>>> y = x**2 >>> y = x**3

>>> plot(x, y) >>> plot(x, y)

>>> show() >>> show()

3
3) f(x) = x^2, g(x) = x^3 in [1,1] 4) f(x) = sinx in [-2pi, 2pi]
Sol. :- >>> from pylab import* Sol. :- >>> from pylab import*
>>> import numpy as np >>> import numpy as np
>>> x = np.linspace(-1, 1, 10) >>> x = np.linspace(-2*pi, 2*pi)
>>> f = x**2 >>> f = np.sin(x)
>>> g = x**3
>>> plot(x, f)
>>> plot(x, f)
>>> show()
>>> plot(x, g)
>>> show()

5) f(x) = e^(x) in [-10, 10] 6) f(x) = 1 + x + 2(x^2) + 3(x^3) + 4(x^4) in [-10, 10]
Sol. :- >>> from pylab import* Sol. :- >>> from pylab import*
>>> import numpy as np >>> import numpy as np
>>> x = np.linspace(-10, 10, 50) >>> x = np.linspace(-10, 10, 100)
>>> f = np.exp(x) >>> f = 1 + (x)+(2*(x**2))+(3*(x**3))+(4*(x**4))
>>> plot(x, f) >>> plot(x, f)
>>> show() >>> show()

4
# Legends, Labels, Titles :-
➢ title() :- To set the title, we use Title attribute after plotting the graphs. Title is written
in LaTex.
➢ xlabel(‘x’), ylabel(‘y’), etc. :- We use this Functions to access the labels.
➢ legend() :- We use this function for legends. Before applying this function, we need to
label the graphs.
Que.) Plot the graphs for the following :-

1) f(x) = x^2 in [0, 5] 2) f(x) = sin x, g(x) = cos x in [-2pi, 2pi]

Sol. :- >>> from pylab import* Sol.:- >>> x = np.linspace(-2*pi, 2*pi, 100)

>>> import numpy as np >>> f = np.sin(x)

>>> x = np.linspace(0, 5, 10) >>> g = np.cos(x)

>>> y = x**2 >>> plot(x, f, label = “$\sin x$”)

>>> plot(x, y, label = “$y = x^2$”) >>> plot(x, g, label = “$\cos x$”)

>>> xlabel(‘x’) >>> xlabel(‘x’)

>>> ylabel(‘y’) >>> ylabel(‘y’)

>>> title(‘Graph of $y = x^2$’) >>> title(‘Graph of $f(x)=\sin x and g(x)=\cos x $’)

>>> legend() >>> legend()

>>> show() >>> show()

5
• Loc :- The legend() takes an optional argument loc that can be used to specific location of
legend.
Python Code Location of Legend
legend(loc = 1) Upper Right Corner

legend(loc = 2) Upper Left Corner

legend(loc = 3) Lower Left Corner

legend(loc = 4) Lower Right Corner

legend(loc = 0) Matplotlib will decide the optional location

Que.) Plot the graphs for the following :-

1) f(x) = 1/x in [-5, 5] 2) f(x) = 1 + (1/x) + (1/(x^2)) in [-5, 5]

Sol. :- >>> from pylab import* Sol. :- >>> from pylab import*

>>> import numpy as np >>> import numpy as np

>>> x = np.linspace(-5, 5, 100) >>> x = np.linspace(-5, 5, 10)

>>> y = 1/x >>> y = 1 + (1/x) + (1/(x**2))

>>> plot(x, y, label = “$y = 1/x$”) >>> plot(x, y, label = “$y = 1 + (1/x) + (1/(x^2))$”)

>>> xlabel(‘x’) >>> xlabel(‘x’)

>>> ylabel(‘y’) >>> ylabel(‘y’)

>>> title(‘Graph of $y = 1/x$’) >>> title(‘Graph of $y = 1 + (1/x) + (1/(x^2))$’)

>>> legend(loc = 1) >>> legend(loc = 2)

>>> show() >>> show()

6
3) f(x) = x.sin(1/(x^2)) in [-5, 5]
Sol.:- >>> from pylab import*
>>> import numpy as np
>>> x = np.linspace(-5, 5, 100)
>>> y = x*np.sin((1/(x**2))
>>> plot(x, y, label = “$y = x.sin(1/(x^2))$”)

>>> xlabel(‘x’)
>>> ylabel(‘y’)
>>> title(‘Graph of $y = x.sin(1/(x^2))$’)

>>> legend(loc = 3)
>>> show()

7
Practical No. 02 :- Graph Plotting – II (2D)
# Setting Colours, Linewidths & Linestyle :-
- To set particular colour to graph mention it in the plot() only.
Example. >>> plot(x, y, ’r’) - - - where ‘r’ stands for red.

Colour Description
y Yellow
m Magenta
c Cyan
r Red
g Green
b Blue
w White
k Black

- To change line width, we use the linewidth or lw keyword argument.


Example. >>> plot(x, y, ’r’, lw = 0.5)

- The line style can be selected using linestyle or ls keyword argument.

Line Style Description

- Solid Line

-- Dashed Line

: Dotted Line

-. Dash Dotted Line

8
- The line marker can be selected using marker keyword argument.

Marker Description

O Circle

+ Plus

* Asterrek

. Point

x Cross

- Horizontal Line

_ Vertical Line

s Square

d Diamond

^ Upward Pointing Triangle

v Downward Pointing Triangle

? Right Pointing Triangle

! Left Pointing Triangle

P Pentagram

h Hexagram

Que.) Plot the graphs for the following :-

1) f(x) = log x in [0, 10]

Sol. :- >>> x = np.linspace(0, 10, 100)


>>> y = np.log(x)
>>> plot(x, y, ’r’, ls = ‘--')
>>> xlabel(‘x’)
>>> ylabel(‘y’)
>>> title(‘$y = \log x$’)
>>> show()

9
2) f(x) = log x in [0, 10] 3) f(x) = log x in [0, 10]
Sol. :- >>> x = np.linspace(0, 10, 100)
Sol. :- >>> from pylab import*
>>> y1 = np.log(x)
>>> import numpy as np
>>> y2 = np.log(x) + 5
>>> from math import* >>> y3 = np.log(x) - 5

>>> x = np.linspace(0, 10, 100) >>> plot(x, y1, ’r’, lw = 0.5)


>>> plot(x, y2, ’b’, lw = 1)
>>> y = np.log(x)
>>> plot(x, y3, ’g’, lw = 3)
>>> plot(x, y, ’r’)
>>> xlabel(‘x’)
>>> xlabel(‘x’) >>> ylabel(‘y’)

>>> ylabel(‘y’) >>> title(‘Graph of $y = \log x$’)


>>> show()
>>> title(‘Graph of $y = \log x$’)

>>> show()

10
4) f(x) = sin x, g(x) = cos x in [-2pi, 2pi] 5) f(x) = x^4 in [0, 5]
Sol. :- >>> from pylab import* Sol. :- >>> from pylab import*
>>> import numpy as np >>> import numpy as np
>>> from math import* >>> x = np.linspace(0, 5, 10)
>>> x = np.linspace(-2*pi, 2*pi, 100) >>> y = x**4
>>> f = np.sin(x) >>> plot(x, y, ”--or”, label = “$y = x^4$”)
>>> g = np.cos(x) >>> xlabel(‘x’)
>>> plot(x, f, label = “$\sin x$”, marker = ‘o’) >>> ylabel(‘y’)
>>> plot(x, g, label = “$\cos x$”, marker = ‘+’) >>> title(‘Graph of $y = x^4$’)
>>> xlabel(‘x’) >>> legend()
>>> ylabel(‘y’) >>> show()
>>> title(‘Graph of $f(x)=\sin x and g(x)=\cos x $’)
>>> legend()
>>> show()

6) f(x) = e^{-x^2} in [-5, 5]


Sol. :- >>> from pylab import*
>>> import numpy as np
>>> x = np.linspace(-5, 5, 100)
>>> y = np.exp(-x**2)
>>> plot(x, y, ”-.^g”, label = “$y = x^4$”)
>>> xlabel(‘x’)
>>> ylabel(‘y’)
>>> title(‘Graph of $y = e^{-x^2}$’)
>>> legend()
>>> show()
11
7) f(x) = (e^x)*(sin x) in [-5*pi, 5*pi]

Sol.:- >>> from pylab import*

>>> import numpy as np

>>> from math import*

>>> x = np.linspace(-5*pi, 5*pi, 100)

>>> y = np.exp(x)*np.sin(x)

>>> plot(x, y, ”:^b”, label = “$y = e^x \sin x$”)

>>> xlabel(‘x’)

>>> ylabel(‘y’)

>>> title(‘Graph of $y = e^x \sin x$’)

>>> legend()

>>> show()

8) f(x) = x^4 in [0, 5]

Sol.:- >>> from pylab import*

>>> import numpy as np

>>> x = np.linspace(0, 5, 10)

>>> y = x**4

>>> plot(x, y, ”--or”, label = “$y = x^4$”)

>>> xlabel(‘x’)

>>> ylabel(‘y’)

>>> xlim([2, 4])

>>> title(‘Graph of $y = x^4$’)

>>> legend()
>>> show()
12
# Subplot() :- subplot(r, c, n)
- We use this function to include multiple graphs in one figure.
Que.) Plot the graphs for the following :-
1) sin x, cos x, e^x, x^2 in [0, 5]
Sol.:- >>> from pylab import*
>>> import numpy as np
>>> from math import*
>>> x = np.linspace(0, 5, 10)
>>> y1 = np.sin(x)
>>> y2 = np.cos(x)
>>> y3 = np.exp(x)
>>> y4 = x**2
>>> subplot(2, 2, 1)
>>> plot(x, y1, label="$\sin x$"
>>> legend()
>>> subplot(2, 2, 2)
>>> plot(x, y2, label="$\cos x$")
>>> legend()
>>> subplot(2, 2, 3)
>>> plot(x, y3, label="$\exp x$")
>>> legend()
>>> subplot(2, 2, 4)
>>> plot(x, y2, label="$x^2$")
>>> legend()
>>> show()

13
2) e^x, e^(-x), e^(1/x) in [0, 5]
Sol. :- >>> x = np.linspace(0,5,100)
>>> y1 = np.exp(x)
>>> y2 = np.exp(-x)
>>> y3 = np.exp(1/x)
>>> subplot(3,1,1)
>>> plot(x,y1,label="$e^x$")
>>> legend()
>>> subplot(3,1,2)
>>> plot(x,y2,label="$e^{-x}$")
>>> legend()
>>> subplot(3,1,3)
>>> plot(x,y3,label="$e^{1/x}$")
>>> legend()
>>> show()

3) e^(-0.5x), e^(-1.0x), e^(-1.5x), e^(-2.0x) in [0, 5]


Sol. :- >>> x = np.linspace(0, 5, 100)
>>> y1 = np.exp(-0.5*x)
>>> y2 = np.exp(-1.0*x)
>>> y3 = np.exp(-1.5*x)
>>> y4 = np.exp(-2.0*x)
>>> subplot(2, 2, 1)
>>> plot(x, y1,l abel="$e^{-0.5*x}$")
>>> legend()
>>> subplot(2, 2, 2)
>>> plot(x, y2, label="$e^{-1.0*x}$")
>>> legend()
>>> subplot(2, 2, 3)
>>> plot(x, y3, label="$e^{-1.5*x}$")
>>> legend()
>>> subplot(2, 2, 4)
>>> plot(x, y2, label="$e^{-2.0*x}$")
>>> legend()
>>> show()

14
# Text Annotation :- text(xvalue, yvalue, text, fontsize, color)

- Text annotation in matplotlib figures can be done using text().

Que.) Plot the graphs for the following :-

1) f(x) = x^2, g(x) = x^3 in [-1, 1]

Sol. :- >>> from pylab import*

>>> import numpy as np

>>> x = np.linspace(-1,1,1000)

>>> f = x**2

>>> g = x**3

>>> plot(x,f,label = "$x^2$",color = "blue")

>>> plot(x,g,label = "$x^3$",color = "green")

>>> text(0.15, 0.2, r"$y = x^2$", fontsize = 20, color = "blue")

>>> text(0.55, 0.1, r"$y = x^3$", fontsize = 20, color = "green")

>>> xlabel('x')

>>> ylabel('y')

>>> legend()

>>> show()

15
2) f(x) = 3(x^4) + 2(x^3) + 7(x^2) + 2x + 9, g(x) = 52(x^3) + 9(x) + 2 in [-10, 10]
Sol. :- >> > x = np.linspace(-10,10,1000)
>>> f = 3*x**4 + 2*x**3 + 7*x**2 + 2*x + 9

>>> g = 5*x**3 + 9*x + 2


>>> plot(x,f,label = "$f(x)$")
>>> plot(x,g,label = "$g(x)$")
>>> xlabel('x')
>>> ylabel('y')
>>> legend()
>>> show()

3) f(x) = e^(-x).sin(2x + 3) in [-10, 10]


Sol. :- >>> x = np.linspace(0,10,1000)
>>> f = np.exp(-x)*np.sin(2*x + 3)
>>> plot(x,f,label = "$e^{-x}\sin(2*x + 3)$")
>>> xlabel('x')
>>> ylabel('y')
>>> ylim([-1,1])
>>> legend()
>>> show()

16
4) f(x) = e^(-1.5x).sin(10x), g(x) = e^(-2x).sin(10x) in [0, 5]
Sol. :- >>> x = np.linspace(0,5,1000)
>>> f = np.exp(-1.5*x)*np.sin(10*x)
>>> subplot(1,2,1)
>>> plot(x,f,label = "$y = e^{-1.5*x}\sin(10*x)$")
>>> g = np.exp(-2*x)*np.sin(10*x)
>>> xlabel('x')
>>> ylabel('y')
>>> ylim([-1,1])
>>> legend()
>>> subplot(1,2,2)
>>> plot(x,g,label = "$y = e^{-2*x}\sin(10*x)$")
>>> xlabel('x')
>>> ylabel('y')
>>> ylim([-1,1])
>>> legend()
>>> show()

17
5) f(x) = e^(-x/2)*sin(2*pi*x) in [-5, 5]
Sol. :- >>> x = np.linspace(-5,5,1000)
>>> y = np.exp(-x/2)*np.sin(2*np.pi*x)
>>> plot(x,y,label = "$y = e^{-x/2}\sin(2\pi*x)$")
>>> xlabel('x')
>>> ylabel('y')
>>> title('Graph of $y = e^{-x/2}\sin(2\pi*x)$')
>>> legend()
>>> show()

6) f(x) = x*sin(x) in [-10, 10]

Sol. :- >>> from pylab import*

>>> import numpy as np

>>> from math import*

>>> x = np.linspace(-10,10,1000)

>>> y = x*np.sin(x)

>>> plot(x,y,label = "$x\sin x$")

>>> xlabel('x')

>>> ylabel('y')

>>> title('Graph of $x\sin x$')

>>> legend()

>>> show()
18
Practical No. 03 :- Graph Plotting – I (3D)

# 3D Counter Plots :-
• mplot3d :- Toolkit is used to create simple 3D plots in matplotlib by supplying an
axes object that can create a 2D projection of 3D scene by axes (projection = ‘3D’)
function.
• ax.contour3D() :- This function creates 3D contour plots. It requires all input data
to be in the form of 2D regular girds with z-data evaluated at each point.
• meshgird() :- 2D regular girds can be generate using this function.
• ax.contour3D(X, Y, Z, n) :- X, Y is domain vectors where we have to plot graph. Z is
2D mesh point. N is number of contour line.

Que.) Plot the graphs for the following :-

1) f(x) = sin(x^2 + y^2) in [-6, 6]

Sol. :- >>> from mpl_toolkits import mplot3d


>>> import numpy as np
>>> from pylab import*
>>> def f(x,y):
return np.sin(np.sqrt(x**2 + y**2))
>>> x = np.linspace(-6, 6, 30)
>>> y = np.linspace(-6, 6, 30)
>>> X, Y = np.meshgrid(x,y)
>>> Z = f(X, Y)
>>> ax = axes(projection = '3d')
>>> ax.contour3D(X, Y, Z, 50)
>>> xlabel('x')
>>> ylabel('y')
>>> title('3D contour')
>>> legend()
>>> show()
19
2) f(x) = x^2 + y^2 in [-6, 6]
Sol. :- >>> def f(x,y):
return x**2 + y**2
>>> x = np.linspace(-6, 6, 30)
>>> y = np.linspace(-6, 6, 30)
>>> X, Y = np.meshgrid(x,y)
>>> Z = f(X, Y)
>>> ax = axes(projection = '3d')
>>> ax.contour3D(X, Y, Z, 50)
>>> xlabel('x')
>>> ylabel('y')
>>> title('3D contour')
>>> legend()
>>> show()

3) f(x) = e^(-x^2 - y^2) in [-1, 1]


Sol. :- >>> def f(x,y):
return np.exp(-x**2 -y**2)
>>> x = np.linspace(-1, 1, 30)
>>> y = np.linspace(-1, 1, 30)
>>> X, Y = np.meshgrid(x,y)
>>> Z = f(X, Y)
>>> ax = axes(projection = '3d')
>>> ax.contour3D(X, Y, Z, 50)
>>> xlabel('x')
>>> ylabel('y')
>>> title('3D contour')
>>> legend()
>>> show()

20
4) f(x) = sin^(4x) – cos^(5y) in [-1, 1]
Sol. :- >>> def f(x, y):
return(np.sin(4*x) - np.cos(5*y))/5

>>> x = np.linspace(-1, 1, 30)


>>> y = np.linspace(-1, 1, 30)
>>> X, Y = np.meshgrid(x,y)
>>> Z = f(X, Y)
>>> ax = axes(projection = '3d')
>>> ax.contour3D(X, Y, Z, 50)
>>> xlabel('x')
>>> ylabel('y')
>>> title('3D contour')
>>> legend()
>>> show()

21
Practical No. 04 :-Graph Plotting – II (3D)
# Wireframes and surface Plots :-
• Surface Plots :- It express a functional association between dependent variable (z)
and two independent variables (x, y). It shows the topology of the surface that being
visualized.
• plot_surface() :- This function having X,Y,Z as arguments is used to plot surface plot,
where X and Y are 2D array of x and y points and Z is 2D array of heights.

Que.) Plot the graphs for the following :-

1) f(x) = x^2 + y^2 in [-6, 6]

Sol. :- >>> from mpl_toolkits import mplot3d

>>> import numpy as np

>>> from pylab import*

>>> def f(x, y):

return x**2 + y**2

>>> x = np.linspace(-6, 6, 30)

>>> y = np.linspace(-6, 6, 30)

>>> X, Y = np.meshgrid(x,y)

>>> Z = f(X, Y)
>>> ax = axes(projection = '3d')

>>> ax.plot_surface(X, Y, Z)

>>> xlabel('x')

>>> ylabel('y')

>>> title('3D contour')

>>> legend()

>>> show()
22
2) f(x) = x*e^(-x^2 - y^2) in [-6, 6]

Sol. :- >>> from mpl_toolkits import mplot3d

>>> import numpy as np

>>> from pylab import*

>>> def f(x,y):

return x*np.exp(-x**2 -y**2)

>>> x = np.linspace(-6, 6, 30)

>>> y = np.linspace(-6, 6, 30)

>>> X, Y = np.meshgrid(x, y)

>>> Z = f(X, Y)
>>> ax = axes(projection = '3d')

>>> ax.plot_surface(X, Y, Z)

>>> xlabel('x')

>>> ylabel('y')

>>> title('$f = x*e^{-x^z -y^2}$')

>>> legend()

>>> show()

23
3) f(x) = cos(|x| + |y|) in [-1, 1]
Sol. :-
>>> def f(x,y):
return np.cos(abs(x) + abs(y))
>>> x = np.linspace(-1, 1, 30)
>>> y = np.linspace(-1, 1, 30)
>>> X, Y = np.meshgrid(x, y)
>>> Z = f(X, Y)
>>> ax = axes(projection = '3d')
>>> ax.plot_surface(X, Y, Z)
>>> xlabel('x')
>>> ylabel('y')
>>> title('$f = cos(|x| + |y|)$')
>>> legend()
>>> show()

4) f(x) = cos(x^2 + y^2 – 0.5)-0.5 in [-1, 1]


Sol. :- >>> def f(x,y):
return np.cos(x**2 + y**2 - 0.5)-0.5
>>> x = np.linspace(-1, 1, 30)
>>> y = np.linspace(-1, 1, 30)
>>> X, Y = np.meshgrid(x, y)
>>> Z = f(X, Y)
>>> ax = axes(projection = '3d')
>>> ax.plot_surface(X, Y, Z)
>>> xlabel('x')
>>> ylabel('y')
>>> title('$\cos(x^2 + y^2 - 0.5) - 0.5$')
>>> legend()
>>> show()

24
# Wire-frame Plots :- It is similar to surface plots, but on wire-frame plot the
entire 3D surface is not shown.
• plot_wireframe() :- Using this method we can construct wire-frame 3D surface plots.
• We need to provide number of rows and column steps as rstride and cstride.
Que.) Plot the graphs for the following :-
1) f(x) = x*e^(-x^2 - y^2) in [-6, 6]
Sol. :- >>> from mpl_toolkits import mplot3d
>>> import numpy as np
>>> from pylab import*
>>> def f(x,y):
return x*np.exp(-x**2 -y**2)
>>> x = np.linspace(-6, 6, 30)
>>> y = np.linspace(-6, 6, 30)
>>> X, Y = np.meshgrid(x, y)
>>> Z = f(X, Y)
>>> ax = axes(projection = '3d')
>>> ax.plot_wireframe(X, Y, Z, rstride = 2, cstride = 2)
>>> xlabel('x')
>>> ylabel('y')
>>> title('$f = x*e^{-x^z -y^2}$')
>>> legend()
>>> show()

2) f(x) = sin(x) + cos(y) in [-5, 5]


Sol. :- >>> def f(x,y):
return np.sin(x) + np.cos(y)
>>> x = np.linspace(-5, 5, 30)
>>> y = np.linspace(-5, 5, 30)
>>> X, Y = np.meshgrid(x, y)
>>> Z = f(X, Y)
>>> ax = axes(projection = '3d')
>>> ax.plot_wireframe(X, Y, Z, rstride = 2, cstride = 2)
>>> xlabel('x')
>>> ylabel('y')
>>> title('$sin(x) + cos(y)$')
>>> legend()
>>> show()
25
Practical No. 05 & 06 :- Application to
Computational Geometry – Points and Lines

# SymPy Module :- This module allows us to 2D geometrical objects such as points,


lines, polygens and circles, and gives information about these objects like area of an ellipse,
checking for collinearity of a set of points, or finding the intersection with numerical values.
# Points :-
➢ In 2D, a point(x, y) is represented by :-
• Row matrix = matrix [ x y ]
• Column matrix = matrix x
y
➢ In 3D, a point(x, y, z) is represented by :-
• Row matrix = matrix [ x y z ]
• Column matrix = matrix x
y
z
➢ To import sympy module :- >>> from sympy import*
➢ Point(x, y) :- Using this function we can represent 2D points.
➢ Point.is.coplanar() :- Using this function we can check whether given points are coplanar or not.
➢ Point.is.collinear() :- Using this function we can check whether given points are collinear or not.
➢ Distance() :- Using this function we can calculate distance between two points.
Example :- >>> x = Point( 0, 0, 0 ) Example :- >> p = Point( 0, 0 )

>>> y = Point( 2, 2, 2 ) >>> q = Point( 2, 2 )


>>> z = Point( -1, -1, -1 ) >>> z = Point( -1, -1 )
>>> w = Point( 3, 4, -7 ) >>> w = Point( 3, 4 )
>>> Point.is.collinear( x, y, z ) >>> x.distance( y )
True 2*sqrt( 2 )
>>> Point.is.collinear( x, y, w ) >>> y.distance( w )
False sqrt( 5 )
>>> Point.is.coplanar( x, y, z, w ) >>> x.distance( z )
True sqrt( 2 )

26
# Transformation Of Points :-
1) Scaling :- It can be done by multiplying matrix [ T ] = a 0 to point X = [x, y], we get,
0 d
[ X ][ T ] = [ x y ] a 0 = [ ax dy ] = [ x* y* ]
0 d

- In this case, we get scaling of both X and Y co-ordinates by factor ‘a’ and ‘d’ respectively. This
can be evaluate using X.scale(a, d) as follows :
>>> x = Point(3, 4)
>>> x.scale(2, 2) >>> x.scale(1, 0) >>> x.scale(3, 7)
Point2D(6, 8) Point2D(3, 0) Point2D(9, 28)

2) Reflection :-
• if b = c = 0, d = 1, a = -1, then [T] = -1 0 , Applying it on X, we get,
0 1
[ X ][ T ] = [ x y ] -1 0 = [ -x y ] = [ x* y* ]
0 1

- Here there is change in the sign of X co-ordinate whereas Y co-ordinate remains same.
Hence [ T ] gives reflection through Y-axis. This can be done by X.transform(matrix).

- 3x3 matrix for reflection through Y-axis will be :- -1 0 0

0 1 0

0 0 1

>>> x = Point( 3, 4 )

>>> x.transform(Matrix([[ -1, 0, 0 ],[ 0, 1, 0 ],[ 0, 0, 1 ]]))

Point2D( -3, 4 )

• if b = c = 0, d = -1, a = 1, then [T] = 1 0 , Applying it on X, we get,


0 -1
[ X ][ T ] = [ x y ] 1 0 = [ x -y ] = [ x* y* ]
0 -1

- 3x3 matrix for reflection through X-axis will be:- 1 0 0

0 -1 0
0 0 1

>>> x = Point( 1, 4 )
>>> x.transform(Matrix([[ 1, 0, 0 ],[ 0, -1, 0 ],[ 0, 0, 1 ]]))
Point2D( 1, -4 )
27
• if b = c = 0, a = d = -1, then [T] = 1 0 , Applying it on X, we get,
0 -1
[ X ][ T ] = [ x y ] -1 0 = [ -x -y ] = [ x* y* ]
0 -1
- 3x3 matrix for reflection through Origin will be :- -1 0 0
0 -1 0
0 0 1

>>> x =Point( -2.3, -4 )

>>> x.transform(Matrix([[ -1, 0, 0 ],[ 0, -1, 0 ],[ 0, 0, 1 ]]))

Point2D( -2.3, -4 )

• if b = c = 1, a = d = 0, then [T] = 0 1 , Applying it on X, we get,


1 0
[ X ][ T ] = [ x y ] 0 1 = [ y x ] = [ x* y* ]
1 0
- 3x3 matrix for reflection through Y = X will be :- 0 1 0
1 0 0
0 0 1
>>> x = Point( 6, -4 )
>>> x.transform(Matrix([[ 0, 1, 0 ],[ 1, 0, 0 ],[ 0, 0, 1 ]]))
Point2D( 4, 6 )
• if b = c = -1, a = d = 0, then [T] = 0 -1 , Applying it on X, we get,
-1 0
[ X ][ T ] = [ x y ] 0 -1 = [ y x ] = [ x* y* ]
-1 0
- 3x3 matrix for reflection through Y = -X will be :- 0 -1 0
-1 0 0
0 0 1
>>> x = Point( 3, -2 )
>>> x.transform(Matrix([[ 0, -1, 0 ],[ -1, 0, 0 ],[ 0, 0, 1 ]]))
Point2D( 2, -3 )

➢ .reflect(Line( ax + by - c )) :- This function is used to reflect points through line ax + by = c. ( a, b != 0 ).


28
Que. ) Reflect the given points through respective lines.

1) (3, 6) , x + y = 0 2) (2, 6) , 2x + y = -1

Sol. :- >>> x, y = symbols(‘x y’) Sol. :- >>> x, y = symbols(‘x y’)

>>> p = Point(3, 6) >>> p = Point(2, 6)

>>> p.reflect(Line(x + y)) >>> p.reflect(Line(2*x + y + 1))

Point2D(-6, -3) Point2D(-34/5, 8/5)

3) (0, -2) , x + y = 5 2) (1.5, 3.6) , x - 2y = 1

Sol. :- >>> x, y = symbols(‘x y’) Sol. :- >>> x, y = symbols(‘x y’)

>>> p = Point(0, -2) >>> p = Point(1.5, 3.6)

>>> p.reflect(Line(x + y)) >>> p.reflect(Line(x – 2*y - 1))

Point2D(7, 5) Point2D(259/50, -44/25)

4) (-5, -6) , -4x + 3y = 11 2) (3, 6) , x - 2y + 4 = 0

Sol. :- >>> x, y = symbols(‘x y’) Sol. :- >>> x, y = symbols(‘x y’)

>>> p = Point(-5, -6) >>> p = Point(3, 6)

>>> p.reflect(Line(x + y)) >>> p.reflect(Line(2*x + y + 1))

Point2D(-197/25, -96/25) Point2D(3, 2)

3) Shearing :-
• if c = 0, a = d = 1, then [T] = 1 b , Applying it on X, we get,
0 1
[ X ][ T ] = [ x y ] 1 b = [ x bx+y ] = [ x* y* ]
0 1

- 3x3 matrix for shearing in X-direction will be :- 1 b 0


0 1 0
0 0 1

>>> x = Point( 3, -4 )

#shearing in X-direction by 3 units

>>> x.transform(Matrix([[ 1, 3, 0 ],[ 0, 1, 0 ],[ 0, 0, 1 ]]))

Point2D(3, 5)

29
• if b = 0, a = d = 1, then [T] = 1 0 , Applying it on X, we get,
c 1
[ X ][ T ] = [ x y ] 1 0 = [ x+cy y ] = [ x* y* ]
c 1
- 3x3 matrix for shearing in Y-direction will be :- 1 0 0
c 1 0
0 0 1
>>> y = Point( 3, -1 )
#shearing in y-direction by 7 units
>>> x.transform(Matrix([[ 1, 0, 0 ],[ 7, 1, 0 ],[ 0, 0, 1 ]]))
Point2D( -4, -1 )
4) Rotation :- In 2D space, rotation takes lace about a fixed point which is called as centre of
rotation. We have transformation matrix for rotation about origin. The transformation matrix for
rotation about origin through an angle 𝜃 is given by ,
➢ .rotate( 𝜽 ) :- Rotation can be done by using this function.
[ T ] = cos 𝜃 sin 𝜃
-sin 𝜃 cos 𝜃
>>> x = Point( 1, 4 )
>>> y = Point( -4, 7 )
>>> x.rotate( pi / 3 )

Point2D( -7*sqrt(3)/2 – 2, 7/2 – 2*sqrt(3))

Que.) Apply each of the following transformations on the point = [4,3]


1) Reflection through Y-axis 5) Shearing in Y-direction by 3 units
Sol. :- >>> from sympy import* Sol. :- >>> p.transform(Matrix([[1,0,0],[3,1,0],[0,0,1]]))
>>> p = Point(4,3) Point2D(13, 3)
>>> p.transform(Matrix([[-1,0,0],[0,1,0],[0,0,1]]))
Point2D(-4, 3)
2) Sacling in X-coordinate by factor 3 6) Scaling in X and Y-direction by 3/2 and 2 units
Sol. :- >>> p.scale(3,0) Sol. :- >>> p.scale(3/2,2)
Point2D(12, 0) Point2D(6, 6)
3) Sacling in Y-coordinate by factor 3.2 7) Shearing in X and Y-direction by -3 and 1 units
Sol. :- >>> p.scale(0,3.2) Sol. :- >>> p.transform(Matrix([[1,-3,0],[1,1,0],[0,0,1]]))
Point2D(0, 48/5) Point2D(7, -9)
4) Reflection through the line y = -x 8) Rotation about origin by an angle 45 degrees
Sol. :- >>> x,y = symbols('x,y') Sol. :- >>> p.rotate(pi/4)
>>> p.reflect(Line(x + y + 0)) Point2D(sqrt(2)/2, 7*sqrt(2)/2)
>>> Point2D(-3, -4)
30
# Lines :-
➢ Line :- A line is a 1D figure, which has length but no width. It is made of a
set of points which is extended in opposite directions infinitely. It
determined by two points in a 2D plane.
Example. :-
• Line L passing through points(a,b) and (c,d) ,
>>> l = Line(Point(a,b),Point(c,d))
• Line corresponding to an equation in the form ax + by + c = 0 ,
>>> l = Line(a*x + b*y - c)
>>> l
• Line with point(a,b) and slope = x ,
>>> l = Line(Point(a,b), slope=x)
>>> l
➢ Equation Of Line :- We use l.equation() and l.coefficients to display the
equation and its coefficients.
➢ Line Segment :- The line segment s can be specified by its end point.
Example. :-
• s having end points (0,0) and (0,1) is define as ,
>>> s = Segment((0,0),(0,1))
>>> s
Segment2D(Point2D(0,0),Point2D(0,1))
➢ Ray :- A Ray is semi-line in the space with a source point and a direction. It
can be specified by two points one of is source point.
➢ s having end points (0,0) and (3,1) is define as ,
>>> r = Ray((0,0),(3,1))
>>> r
Ray2D(Point2D(0,0),Point2D(3,1))

31
# Functions related to Lines, Rays and Segments :-
1) Angle between two linear entities(lines, rays, segments) :- We can find
angle formed by intersection of linear entities using .angle_between()
2) Intersection points of two linear entities :- We can find intersection
point formed by intersection of linear entities using .intersection()
3) Length of linear entities :- We can find length of linear entities using
.length.(Length of line and ray = ∞)
4) Distance :- We can find shortest distance between the linear entities and
the points using .distance()
5) Slope of linear entities :- We can find slope of any linear entities using
.slope
6) Midpoint of segment :- We can find midpoint of segment using
.midpoint
7) Points of linear entities :- We can display the two points of any linear
entities using .points
8) Rotation of linear entities :- We can do counter clockwise rotation of any
linear entities using .rotate(angle). Where the angle should be in radians.
9) Reflection of linear entities :- We can do reflection through a line of any
linear entities using .reflect(line)
10) Transformation of linear entities :- A straight line can be determined by
two points that lie on it, so any transformation on the line can be
achieved by transforming the points on the line.
Que.) Solve the following examples on linear entities :-
1) l = Line((0,0),(0,3)), s = Segment((0,0),(0,1)), r = Ray((0,0),(8,8))
Sol.:- >>> l.angle_between(s) >>> s.length
0 1
>>> l.angle_between(r) >>> r.length
pi/4 00
>>> l.intersection(s) >>> l.length
[Segment2D(Point2D(0, 0), Point2D(0, 1))] 00
>>> l.intersection(r)
[Point2D(0, 0)]

32
2) Line segment between points A[1 4], B[3 6] is transformed to line
segment A*B* using transformation matrix [T] = 2 -1 . Find the slope of
transformed line segment A*B*. 1 3
Sol. :->>> from sympy import * Matrix = 2 -1 0
>>> A = Point(1,4) 1 3 0
>>> B = Point(3,6) 0 0 1
>>> a = A.transform(Matrix([[2,-1,0],[1,3,0],[0,0,1]]))
>>> b = B.transform(Matrix([[2,-1,0],[1,3,0],[0,0,1]]))
>>> l = Segment(a,b)
>>> l.slope
2/3
3) If the line segment the joining points A[2 5], B[4 -13] is transformed to
line segment A*B* by the transformation matrix [T] = 2 3 , then find
midpoint of A*B*. 4 1
Sol.:- >>> A = Point(2,5) Matrix = 2 3 0
>>> B = Point(4,-13) 4 1 0
>>> a = A.transform(Matrix([[2,3,0],[4,1,0],[0,0,1]])) 0 0 1
>>> b = B.transform(Matrix([[2,3,0],[4,1,0],[0,0,1]]))
>>> l = Segment(a,b)
>>> l.midpoint
Point2D(-10,5)
4) Rotate the line passing through points A[1 1], B[5 5] about origin through
angle 90°.
Sol.:- >>> l = Line((1,1),(5,5))
>>> l.rotate(pi/2)
Line2D(Point2D(-1,1),point2D(-5,5))

33
5) Reflect the line segment joining the points A[5 3], B[1 4] through the line
y = x + 1.
Sol.:- >>> x,y = symbols('x,y')
>>> A = Point(5,3)
>>> B = Point(1,4)
>>> s = Segment(A,B)
>>> s.reflect(Line(x - y + 1))
>>> Segment2D(Point2D(2, 6), Point2D(3, 2))
6) If two lines 2*x – y = 5 and x + 3*y = -1 are transformed using [T] = -2 3
then find point of intersection of transformed lies. 1 1
Sol.:- >>> x,y = symbols('x,y')
>>> l1 = Line(2*x - y - 5)
>>> l2 = Line(x + 3*y + 1)
>>> p = l1.intersection(l2)
>>> p = p[0]
>>> p.transform(Matrix([[-2,3,0],[1,1,0],[0,0,1]]))
Point2D(-5, 5)
7) If we apply shearing on line 2*x + y = 3 in x and y directions by 2 and -3
respectively. Find the equation of resulting line.
Sol.:- >>> x,y = symbols('x,y')
>>> l = Line(2*x + y - 3)
>>> points = l.points
>>> p = points[0]
>>> q = points[1]
>>> p1 = p.transform(Matrix([[1,-3,0],[2,1,0],[0,0,1]]))
>>> q1 = q.transform(Matrix([[1,-3,0],[2,1,0],[0,0,1]]))
>>> l1 = Line(p1,q1)
>>> l1.equation()
5*x - 3*y - 21
34
8) If [T] = 1 3 is used to transform a line, then line of equation is y* = x* + 4.
-2 2
Find equation of original line.
Sol.:- >>> from sympy import *
>>> x,y = symbols('x,y')
>>> l = Line(x - y + 4)
>>> points = l.points
>>> p = points[0]
>>> q = points[1]
>>> m = Matrix([[1,3,0],[-2,2,0],[0,0,1]])
>>> n = m.inv()
>>> p1 = p.transform(n)
>>> q1 = q.transform(n)
>>> l1 = Line(p1,q1)
>>> l1.equation()
x/4 + y/2 - ½

35
Practical No. 07 :- Polygon, 2D, 3D Rotation
& Reflection

# Polygon :-
• A polygon can be represented by its vertices. A polygon with vertices
P1(x1,y1), P2(x2,y2), …, Pn(xn,yn)is represented by a matrix as :-
[T] = x1 y1
X2 y2
. .
. .
Xn yn
• A line segment joining the points A(x1,y1) and B(x2,y2) is represented by
[X] = A = x1 y1
B x2 y2
• Triangle with the vertices A(x1,y1), B(x2,y2), C(x3,y3) is represented by
[X] = A = x1 y1
B x2 y2
C x3 y3

• Representing Polygon in python :-


>>> p1, p2, p3, p4, p5 = [(0,0),(1,0),(5,1),(0,1),(3,0)]
>>> p = Polygon(p1, p2, p3, p4, p5)
>>> p
Polygon(Point2D(1,0), Point2D(1,0), Point2D(5,1), Point2D(0,1), Point2D(3,0))

• Regular Polygon :- Such a polygon has all internal angles equal and all sides
the same length. When the keyword is used to define the number of sides of
the Polygon then a RegularPolygon is created and the other arguments are
interpreted as centre, radius and rotation.
>>> p = Polygon((0,0),1,n*5)
>>> p
RegularPolygon(Point2D(0,0), 1, 5, 0)
36
# Important Attributes of Polygon :-
1) Area of Polygon :- To calculate area of polygon we use P.area . The area of a polygon
is calculated as positive when vertices are traversed in a counter-clockwise direction.
2) Angle at vertices :- The internal angle at each vertex can be calcite using
P.angles[point]
3) Convex Polygon :- A polygon is convex if all its interior angles < 180° & there are no
intersections between sides. We can check whether given polygon is convex or not
using is_convex()
4) Perimeter of Polygon :- To calculate perimeter of polygon we use P.perimeter
5) Centre of RegularPolygon :- We can find centre of regular polygon using P.center
6) Reflection :- We can reflect polygon through line using P.reflect(line)
7) Rotation :- We can rotate about a angle using P.rotate(𝜽)
8) Scale :- We can scale the polygon using P.scale()
Example. p1(0,0), p2(1,0), p3(5,1), p4(0,1)
Sol.:- >>> from sympy import *
>>> p1, p2, p3, p4 = map(Point, [(0,0),(1,0),(5,1),(0,1)])
>>> P = Polygon(p1, p2, p3, p4)
>>> P.area >>> P.angles[p1]
3 pi/2
>>> P.angles[p2] >>> P.angles[p3]
acos(-4*sqrt(17)/17) acos(4*sqrt(17)/17)
>>> P.angles[p4] >>> P.is_convex()
>>> pi/2 True
>>> P.perimeter >>> x,y = symbols('x,y')
sqrt(17) + 7 >>> l = Line(x - y)
>>> P = RegularPolygon(Point(0,0), 5, 3) >>> P.reflect(l)
>>> P.center RegularPolygon(Point2D(0, 0), -5, 3, pi/2)
Point2D(0, 0)
>>> P.rotate(pi/4) >>> P.scale(2,2)
RegularPolygon(Point2D(0, 0), 5, 3, pi/4) RegularPolygon(Point2D(0, 0), 10, 3, 0)
>>> P.scale(2,3)
>>> Triangle(Point2D(10, 0), Point2D(-5, 15*sqrt(3)/2), Point2D(-5, -15*sqrt(3)/2))

37
# Triangles :- Polygon with 3 vertices or 3 sides is a triangle.
Example.
Que) p1(0,0), p2(1,0), p3(5,1)
Sol.:- >>> from sympy import *
>>> p1, p2, p3 = [(0,0),(1,0),(5,1)]
>>> P = Polygon(p1, p2, p3)
>>> P
Triangle(Point2D(0, 0), Point2D(1, 0), Point2D(5, 1))
>>> P = Triangle(p1, p2, p3)
>>> P
Triangle(Point2D(0, 0), Point2D(1, 0), Point2D(5, 1))
>>> Triangle(sss = (3,4,5)) # side-side-side
Triangle(Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
>>> Triangle(asa = (30, 1, 30)) # angle-side-angle
Triangle(Point2D(0, 0), Point2D(1, 0), Point2D(1/2, sqrt(3)/6))
>>> Triangle(sas = (1, 45, 2)) # side-angle-side
Triangle(Point2D(0, 0), Point2D(2, 0), Point2D(sqrt(2)/2, sqrt(2)/2))

# Attributes of Triangle :-
1) Isosceles Triangle :- We can check whether 2 or more of the sides the same length.
2) Right Angled Triangle :- We can check whether given triangle is right angle triangle or
not.
3) Scalene Triangle :- We can check whether given triangle is scalene triangle or not.
Example.
>>> T1 = Triangle(Point(0,0), Point(4,0), Point(2,4)) >>> T2 = Triangle(Point(0,0), Point(4,0), Point(4,3))

>>> T1.is_isosceles() >>> T2.is_right()


True True
>>> T3 = Triangle(Point(0,0), Point(4,0), Point(1,4))

>>> T3.is_scalene()
True
38
Que.) Solve the following :-
1) Polygon with vertices (0,0),(1,0),(2,2),(1,4). Find its area and perimeter & rotate it by
180°.
Sol. :- >>> a = Point(0,0) >>> p.area
>>> b = Point(1,0) 4
>>> c = Point(2,2) >>> p.perimeter
>>> d = Point(1,4) 1 + sqrt(17) + 2*sqrt(5)
>>> p =Polygon(a, b, c, d)
>>> p.rotate(pi)
Polygon(Point2D(0, 0), Point2D(-1, 0), Point2D(-2, -2), Point2D(-1, -4))
2) Polygon with 8 sides, radius 5 centered at origin & another polygon with 6 sides,
radius 1 centered at origin. Find their area’s & perimeter’s.
Sol.:- >>> p1 = Polygon((0,0), 5, n=8) >>> p2 = Polygon((1,2), 1, n=6)
>>> p1.area >>> p2.area
(400 – 200*sqrt(2)) / (-4 + 4*sqrt(2)) 3*sqrt(3) / 2
>>> p1.perimeter >>> p2.perimeter
40*sqrt(2 – sqrt(2)) 6
3) Regular polygon with 7 sides, radius 1.5 centered at (2,2). Reflect it through line x-y=5.
Sol. :- >>> x,y = symbols('x,y')
>>> p = Polygon((2,2), 1.5, n=7)
>>> p.reflect(Line(x - y - 5))
RegularPolygon(Point2D(7,-3), -1.5, 7, 3*pi/14)
4) Do the following operations on pol ABC where A[1 0], B[2 -1], C[-1 3] :-
i) Reflect the pol ABC through the line y=3, iii) Find area and perimeter,
ii) Rotate it by 90°, iv) Find angle at each vertices.
Sol.:- >>> from sympy import* >>> t.reflect(Line(y - 3))
>>> x,y = symbols('x,y') Triangle(Point2D(1, 6), Point2D(2, 7), Point2D(-1, 3))
>>> A = Point(1,0) >>> t.rotate(pi/2)
>>> B = Point(2,-1) Triangle(Point2D(0, 1), Point2D(1, 2), Point2D(-3, -1))
>>> C = Point(-1,3) >>> t.area
>>> t = Triangle(A,B,C) 1/2
>>> t.perimeter >>> t.angles[A]
Sqrt(2) + sqrt(13) + 5 acos(-5*sqrt(26)/26)
>>> t.angles[B] >>> t.angles[C]
acos(7*sqrt(2)/10) acos(18*sqrt(13)/65)
39
Practical No. 08 :- Linear Programming in
Python
Que.) Solve the following :-
1) Write a Python program to draw a line 𝑦 = log 𝑥 2 + sin 𝑥 with suitable
label in 𝑥 axis, 𝑦 axis and a title in [−5𝜋, 5𝜋] .
Sol.:- >>> from pylab import*
>>> import numpy as np
>>> x=np.linspace(-5*pi,5*pi,100)
>>> y=np.log(x**2)+np.sin(x)
>>> plot(x,y)
>>> xlabel('x-axis')
>>> ylabel('y-axis')
>>> title('Line of Y is')

>>> show()

40
2) Generate a subplot for the following functions using the Python. i. 𝑦 = 𝑒
−𝑥 sin , = 𝑒 −2𝑥 cos 𝑥 ; 0 ≤ 𝑥 ≤ 4𝜋 (2 × 1
subplots ) ii. 𝑦 = 1 , = 1 𝑥 2 , 𝑦 = 1 𝑥 3 ; −5 ≤ 𝑥 ≤ 5 (1 × 3) subplots
Sol.:- >>> from pylab import*
>>> import numpy as np
>>> x=np.linspace(0,4*pi,100)
>>> y1=exp(-x)*sin(x)
>>> y2=exp(-2*x)*cos(x)
>>> subplot(2,1,1)
>>> plot(x,y1,label="$\exp(-x)*sin(x)$")
>>> legend()
>>> subplot(2,1,2)
>>> plot(x,y2,label="$\exp(-2*x)*cos(x)$")
>>> legend()
>>> show()

41
Practical No. 09 :- Linear Programming in
Python

# Study of Operational Research in Python :-


- Operational research is the use of mathematical models, statistics and
algorithms to aid in decision making. It is used to analyse complex real-world
systems, typically with the goal of improving, optimizing performance. The
primary tools used by operations researchers are statistics, optimization,
stochastics, queueing theory, game theory, graph theory, simulation. The
researchers use customwritten or off-the-shelf software.

# Linear Programming :- (LP)


- LP is the technique used to maximize or minimize a function. We optimize a
function denoted in linear terms & bounded by linear constraints.
• PuLP :-This package is used to solve optimization problems using LP.
• Installation of PuLP :- >>> pip install pulp (# for windows)
• We can import via :- >>> from pulp import *
# Functions used for LPP :-
1) LpProblem() :- This functions creates a new LP Problem with the specified
parameters. We can also create model using this function.
2) LpVariable() :- It is used to assign an LP variable with the specified
associated parameters.
3) .solve() :- It returns the integer status of the solution, which will be 1 if the
optimum is found. For different solution status, it gives different outputs.
Solution Status Numeric Output
1
Optimal
0
Not Solved
-1
Infeasible
-2
Unbounded
-3
Undefined
42
4) objective.value() :- It is used to display optimum value of objective
function.
5) value() :- It is used to display optimum value of associated variables.
6) sense :- We use this parameter to choose whether our problem is of
minimization (LpMinimize or 1) or maximization(LpMaximize or -1).
Que.) Solve the following LPP’s :-
1) Min Z = x + 2y + z
Subject to, x + (1/2)y + (1/2)z ≤ 1
(3/2)x + 2y + z ≥ 8
x,y,z ≥ 0
Sol.:- >>> from pulp import*
>>> model = LpProblem(sense = LpMinimize)
>>> x = LpVariable(name = "x", lowBound = 0)
>>> y = LpVariable(name = "y", lowBound = 0)
>>> z = LpVariable(name = "z", lowBound = 0)
>>> model += (x + 0.5*y + 0.5*z <= 1)
>>> model += (1.5*x + 2*y + z >= 8)
>>> model += x + 2*y + z
>>> model
NoName:
MINIMIZE
1*x + 2*y + 1*z + 0
SUBJECT TO
_C1: x + 0.5 y + 0.5 z <= 1

_C2: 1.5 x + 2 y + z >= 8

VARIABLES
x Continuous
y Continuous
z Continuous
>>> model.solve()
-1
Solution is Infeasible.
43
2) Max Z = 150x + 75y
subject to, 4x + 6y ≤ 24
5x + 3y ≤ 15
x,y ≥ 0
Sol.:- >>> from pulp import*
>>> model = LpProblem(name = "small-problem", sense = LpMaximize)
>>> x = LpVariable(name = "x", lowBound = 0)
>>>> y = LpVariable(name = "y", lowBound = 0)
>>> model += 4*x + 6*y <= 24
>>> model += 5*x + 3*y <= 15
>>> model += 150*x + 75*y
>>> model
small-problem:
MAXIMIZE
150*x + 75*y + 0
SUBJECT TO
_C1: 4 x + 6 y <= 24

_C2: 5 x + 3 y <= 15

VARIABLES
x Continuous
y Continuous

>>> model.solve()
1
>>> model.objective.value()
450.0
>>> x.value()
3.0
>>> y.value()
0.0
Solution is Optimum.

44
3) Min Z = 3.5x + 2y
subject to, x + y ≥ 5
x≥ 4
y≤2
x,y ≥ 0
Sol.:- >>> from pulp import*
>>> model = LpProblem(sense = LpMinimize)
>>> x = LpVariable(name = "x", lowBound = 0)
>>> y = LpVariable(name = "y", lowBound = 0)
>>> model += x + y >= 5
>>> model += x >= 4
>>> model += y <= 2
>>> model += 3.5*x + 2*y
>>> model
NoName:
MINIMIZE
3.5*x + 2*y + 0.0
SUBJECT TO
_C1: x + y >= 5

_C2: x >= 4

_C3: y <= 2

VARIABLES
x Continuous
y Continuous

>>> model.solve()
1

45
4) Max Z = 4x + y + 3z +5w
Subject to 4x + 6y - 5z - 4w ≤ -20
-3x - 2y + 4z + 1w ≤ 15
-8x -3y +3z +2w 20
x,y,z,w ≥ 0
Sol.:- >>> from pulp import*
>>> model = LpProblem(sense = LpMaximize)
>>> x = LpVariable(name = "x", lowBound = 0)
>>> y = LpVariable(name = "y", lowBound = 0)
>>> z = LpVariable(name = "z", lowBound = 0)
>>> w = LpVariable(name = "w", lowBound = 0)
>>> model += 4*x + 6*y - 5*z - 4*w >= -20
>>> model += -3*x - 2*y + 4*z + w <= 10
>>> model += -8*x - 3*y + 3*z + 2*w <= 20
>>> model += 4*x + y + 3*z + 5*w
>>> model
NoName:
MAXIMIZE
5*w + 4*x + 1*y + 3*z + 0
SUBJECT TO
_C1: - 4 w + 4 x + 6 y - 5 z >= -20

_C2: w - 3 x - 2 y + 4 z <= 10

_C3: 2 w - 8 x - 3 y + 3 z <= 20

VARIABLES
w Continuous
x Continuous
y Continuous
z Continuous
>>> model.solve()
-2
Solution is Unbounded.
46
Practical No. 10 :-Transportation Problem

# Transportation problem :- TP is a special kind of LPP in which goods are


transported from a set of sources to a set of destination subject to the supply &
demand of the source & destination respectively such that the total cost of
transportation is minimized. It is also called as Hitchcock Problem.
• Balanced :- when supplies = demands, then it is said to be balanced.
• Unbalanced :- when supplies ≠ demands, then it is said to be balanced. In
this type of problem, either a dummy row or a column is added according
to requirement to make it a balanced problem.

# Basic Structure of TP :-
Destination(Dj)
D1 D2 D3 D4

O1 C11 C12 C13 C14 S1

O2 C21 C22 C23 C24 S2


Supply(Si)
Source(Oi)

O3 C31 C32 C33 C34 S3

O4 C41 C42 C43 C44 S4

d1 d2 d3 d4
Demand(dj)
In the above table D1, D2, D3, D4 are the destinations where the
products/goods are to be delivered from different sources S1, S2, S3, S4. Si is
the supply from source Oi. dj is the demand of destination Dj. Cij is the cost
when the product is delivered from source Si to destination Dj.

47
Que.) A boutique brewery has 2 warehouses from which it distributes beer to 5
carefully chosen bars. At the start of every week, each bar sends an order to the
brewery’s head-office for so many creates to beer, which is then dispatched from the
appropriate warehouses to the bars. The brewery would like to have an interactive
computer program which they can run week by week to tell them which warehouse
should supply which bar so as to minimize the cost of the whole operation. For
example, suppose that at the start of a given week brewery has 1000 cases at
warehouse A, & 4000 cases at warehouses B, & that the bars require 500, 900, 1800,
200, 700 cases respectively. Transportation costs (dollars per crate) is given in the
following table.
From Warehouse to Bar A B
1 2 3
2 4 1
3 5 3
4 2 2
5 1 3
Which warehouse should supply which bar ?
Sol.:- A1 = number of crates of beer to ship from Warehouse A to Bar 1,
A5 = number of crates of beer to ship from Warehouse A to Bar 5,
B1 = number of crates of beer to ship from Warehouse B to Bar 1,
B5 = number of crates of beer to ship from Warehouse B to Bar 5.
Let X(w,b) be the variable assigned to route from warehouse w to bar b.
W = {A,B}
B = {1,2,3,4,5}
X(w,b) ∈ N ∪ {0}
C(w,b) denotes the cost required to transport beer from warehouse w to bar b,

Minimize the Transporting Costs = min∑ 𝑪(𝒘, 𝒃)𝑿(𝒘, 𝒃)


𝒘∈𝑾,𝒃∈𝑩
Now formulate the constraints :-
A1 + A2 + A3 + A4 + A5 ≤ 1000
B1 + B2 + B3 + B4 + B5 ≤ 4000
A1 + B1 ≥ 500
A2 + B2 ≥ 900
A3 + B3 ≥ 1800
A4 + B4 ≥ 200
A5 + B5 ≥ 700
48
>>> from pulp import*
>>> Warehouses = ["A","B"]
>>> supply = {"A" : 1000,
"B" : 4000}
>>> Bars = ["1","2","3","4","5"]
>>> demand = {"1" : 500,
"2" : 900,
"3" : 1800,
"4" : 200,
"5" : 700,}
>>> costs = {"A" : {"1" : 2, "2" : 4, "3" : 5, "4" : 2, "5" : 1},
"B" : {"1" : 3, "2" : 1, "3" : 3, "4" : 2, "5" : 3}}
>>> prob = LpProblem("Beer Distribution Problem", LpMinimize)
>>> Routes = [(w,b) for w in Warehouses for b in Bars]
>>> vars = LpVariable.dicts("Route",(Warehouses,Bars),0,None,LpInteger)
>>> prob += lpSum([vars[w][b] * costs[w][b] for (w,b) in Routes]), "Sum_of_Costs"
>>> for w in Warehouses :
... prob += lpSum([vars[w][b] for b in Bars]) <= supply[w], "Sum_Prod_%s"%w

>>> for b in Bars :


... prob += lpSum([vars[w][b] for w in Warehouses]) >= demand[b], "Sum_Prod_%s"%b

>>> prob.writeLP
<bound method LpProblem.writeLP of Beer_Distribution_Problem:
MINIMIZE
2*Route_A_1 + 4*Route_A_2 + 5*Route_A_3 + 2*Route_A_4 + 1*Route_A_5 +
3*Route_B_1 + 1*Route_B_2 + 3*Route_B_3 + 2*Route_B_4 + 3*Route_B_5 + 0
SUBJECT TO
Sum_Prod_A: Route_A_1 + Route_A_2 + Route_A_3 + Route_A_4 + Route_A_5 <= 1000

Sum_Prod_B: Route_B_1 + Route_B_2 + Route_B_3 + Route_B_4 + Route_B_5 <= 4000

Sum_Prod_1: Route_A_1 + Route_B_1 >= 500

49
Sum_Prod_2: Route_A_2 + Route_B_2 >= 900

Sum_Prod_3: Route_A_3 + Route_B_3 >= 1800

Sum_Prod_4: Route_A_4 + Route_B_4 >= 200

Sum_Prod_5: Route_A_5 + Route_B_5 >= 700

VARIABLES
0 <= Route_A_1 Integer
0 <= Route_A_2 Integer
0 <= Route_A_3 Integer
0 <= Route_A_4 Integer
0 <= Route_A_5 Integer
0 <= Route_B_1 Integer
0 <= Route_B_2 Integer
0 <= Route_B_3 Integer
0 <= Route_B_4 Integer
0 <= Route_B_5 Integer
>

>>> value(prob.objective)
8600.0
>>> for v in prob.variables() :
... print(v.name, "=", v.varValue)

Route_A_1 = 300.0
Route_A_2 = 0.0
Route_A_3 = 0.0
Route_A_4 = 0.0
Route_A_5 = 700.0
Route_B_1 = 200.0
Route_B_2 = 900.0
Route_B_3 = 1800.0
50
Route_B_4 = 200.0
Route_B_5 = 0.0
This gives optimal solution as :
Ship 300 crates of beer from warehouse A to pub 1
Ship 700 crates of beer from warehouse A to pub 5
Ship 200 crates of beer from warehouse B to pub 1
Ship 900 crates of beer from warehouse B to pub 2
Ship 1800 crates of beer from warehouse B to pub 3
Ship 200 crates of beer from warehouse B to pub 4
Que.) The ICARE Company has 3 plants located throughout a state with
production capacity 50,75,25 gallons. Each day the firm must furnish its 4 retail
R1,R2,R3,R4 with at last 20,20,50,60 gallons respectively. The transportation
costs (in Rs.) are given below.

Company R1 R2 R3 R4 Supply
A 3 5 7 6 50
B 2 5 8 2 75
C 3 6 9 2 25
Demand 20 20 50 60
Sol.:- A1 = number of gallons to ship from company A to shop R1,
B2 = number of gallons to ship from company B to shop R2,
Let X(w,r) be the variable assigned to route from company w to shop r.
W = {A,B,C}
B = {1,2,3,4}
X(w,r) ∈ N ∪ {0}
C(w,r) denotes the cost required to transport beer from company w to shop r,

Minimize the Transporting Costs = min∑ 𝑪(𝒘, 𝒓)𝑿(𝒘, 𝒓)


𝒘∈𝑾,𝒓∈𝑩

51
Now formulate the constraints :-
A1 + A2 + A3 + A4 ≤ 50
B1 + B2 + B3 + B4 ≤ 75
C1 + C2 + C3 + C4 ≤ 25
A1 + B1 + C1 ≥ 20
A2 + B2 + C2 ≥ 20
A3 + B3 + C3 ≥ 50
A4 + B4 + C4 ≥ 60
>>> from pulp import*
>>> company = ["A","B","C"]
>>> supply = { "A" : 50,
"B" : 75,
"C" : 25}
>>> shop = ["1","2","3","4"]
>>> demand = {"1" : 20,
... "2" : 20,
... "3" : 50,
... "4" : 60}
>>> costs = {"A" : {"1" : 3, "2" : 5, "3" : 7, "4" : 6},
... "B" : {"1" : 2, "2" : 5, "3" : 8, "4" : 2},
... "C" : {"1" : 3, "2" : 6, "3" : 9, "4" : 2}}
...
>>> prob = LpProblem("Transportation", LpMinimize)

>>> Routes = [(w,r) for w in company for r in shop]


>>> vars = LpVariable.dicts("Route",(company,shop),0,None,LpInteger)
>>> prob += lpSum([vars[w][r] * costs[w][r] for (w,r) in Routes]), "Sum_of_Costs"
>>> for w in company :
... prob += lpSum([vars[w][r] for r in shop]) <= supply[w], "Sum_Prod_%s"%w

>>> for r in shop :


... prob += lpSum([vars[w][r] for w in company]) >= demand[r], "Sum_Prod_%s"%r

>>> prob.writeLP
52
<bound method LpProblem.writeLP of Transportation:
MINIMIZE
3*Route_A_1 + 5*Route_A_2 + 7*Route_A_3 + 6*Route_A_4 + 2*Route_B_1 +
5*Route_B_2 + 8*Route_B_3 + 2*Route_B_4
SUBJECT TO
Sum_Prod_A: Route_A_1 + Route_A_2 + Route_A_3 + Route_A_4 <= 50

Sum_Prod_B: Route_B_1 + Route_B_2 + Route_B_3 + Route_B_4 <= 75

Sum_Prod_C: Route_C_1 + Route_C_2 + Route_C_3 + Route_C_4 <= 25

Sum_Prod_1: Route_A_1 + Route_B_1 + Route_C_1 >= 20

Sum_Prod_1: Route_A_2 + Route_B_2 + Route_C_2 >= 20

Sum_Prod_1: Route_A_3 + Route_B_3 + Route_C_3 >= 50

Sum_Prod_1: Route_A_4 + Route_B_4 + Route_C_4 >= 60

VARIABLES
0 <= Route_A_1 Integer
0 <= Route_A_2 Integer
0 <= Route_A_3 Integer
0 <= Route_A_4 Integer
0 <= Route_B_1 Integer
0 <= Route_B_2 Integer
0 <= Route_B_3 Integer
0 <= Route_B_4 Integer
0 <= Route_C_1 Integer
0 <= Route_C_2 Integer
0 <= Route_C_3 Integer
0 <= Route_C_4 Integer
>

53
>>> value(prob.objective)
610.0
>>> for v in prob.variables() :
... print(v.name, "=", v.varValue)

Route_A_1 = 0.0
Route_A_2 = 0.0
Route_A_3 = 50.0
Route_A_4 = 0.0
Route_B_1 = 20.0
Route_B_2 = 20.0
Route_B_3 = 0.0
Route_B_4 = 35.0
Route_C_1 = 0.0
Route_C_2 = 0.0
Route_C_3 = 0.0
Route_C_4 = 25.0
This gives optimal solution as :-
Ship 50 gallons from company A to shop 3
Ship 20 gallons from company B to shop 1
Ship 20 gallons from company B to shop 2
Ship 35 gallons from company B to shop 4
Ship 25 gallons from company C to shop 4

54

You might also like