0% found this document useful (0 votes)
24 views105 pages

Reference For Solution To Practicals of MTC-243

The document provides a series of Python programs for plotting various mathematical functions using libraries such as NumPy and Matplotlib. Each program includes specific functions to be plotted over defined intervals, along with customization options for colors, labels, and legends. Additionally, it addresses potential runtime warnings related to logarithmic calculations and provides examples of both single and multiple subplots.

Uploaded by

Shweta Pokale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views105 pages

Reference For Solution To Practicals of MTC-243

The document provides a series of Python programs for plotting various mathematical functions using libraries such as NumPy and Matplotlib. Each program includes specific functions to be plotted over defined intervals, along with customization options for colors, labels, and legends. Additionally, it addresses potential runtime warnings related to logarithmic calculations and provides examples of both single and multiple subplots.

Uploaded by

Shweta Pokale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

S.Y.B.Sc. Comp. Sc. Sem-IV Practical no.

1(Graph
Plotting)
In [1]:  pip install numpy

Requirement already satisfied: numpy in c:\users\krush\anaconda3\lib\site-packa


ges (1.24.3)
Note: you may need to restart the kernel to use updated packages.

In [2]:  pip install sympy

Requirement already satisfied: sympy in c:\users\krush\anaconda3\lib\site-packa


ges (1.11.1)
Requirement already satisfied: mpmath>=0.19 in c:\users\krush\anaconda3\lib\sit
e-packages (from sympy) (1.2.1)
Note: you may need to restart the kernel to use updated packages.

In [3]:  pip install matplotlib

Requirement already satisfied: matplotlib in c:\users\krush\anaconda3\lib\site-


packages (3.7.1)
Requirement already satisfied: contourpy>=1.0.1 in c:\users\krush\anaconda3\lib
\site-packages (from matplotlib) (1.0.5)
Requirement already satisfied: cycler>=0.10 in c:\users\krush\anaconda3\lib\sit
e-packages (from matplotlib) (0.11.0)
Requirement already satisfied: fonttools>=4.22.0 in c:\users\krush\anaconda3\li
b\site-packages (from matplotlib) (4.25.0)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\users\krush\anaconda3\li
b\site-packages (from matplotlib) (1.4.4)
Requirement already satisfied: numpy>=1.20 in c:\users\krush\anaconda3\lib\site
-packages (from matplotlib) (1.24.3)
Requirement already satisfied: packaging>=20.0 in c:\users\krush\anaconda3\lib
\site-packages (from matplotlib) (23.0)
Requirement already satisfied: pillow>=6.2.0 in c:\users\krush\anaconda3\lib\si
te-packages (from matplotlib) (9.4.0)
Requirement already satisfied: pyparsing>=2.3.1 in c:\users\krush\anaconda3\lib
\site-packages (from matplotlib) (3.0.9)
Requirement already satisfied: python-dateutil>=2.7 in c:\users\krush\anaconda3
\lib\site-packages (from matplotlib) (2.8.2)
Requirement already satisfied: six>=1.5 in c:\users\krush\anaconda3\lib\site-pa
ckages (from python-dateutil>=2.7->matplotlib) (1.16.0)
Note: you may need to restart the kernel to use updated packages.

Q1. Write a Python program to plot 2D graph of the functions f (x) = x^2 and g(x) = x^3 in
[-1,1].
In [4]:  from pylab import*
import numpy as np
x=np.linspace(-1,1,100)
f=x**2
g=x**3
plot(x,f,'r',label="$f(x) = x^2$")
plot(x,g,'c',label="$g(x) = x^3$")
xlabel('x')
ylabel('y')

title('Graph of $f(x) = x^2$ and $g(x) = x^3$')
legend()
show()

Q2. Write a Python program to plot 2D graph of the functions f (x) = log10(x) in the interval
[0,10]
In [5]:  ​
from pylab import*
import numpy as np
x=np.linspace(0,10,100)
y=np.log10(x)

plot(x,y,'r')
xlabel('x')
ylabel('y')

title('Graph of $y=log10(x)$')
legend(loc=0)
show()

C:\Users\krush\AppData\Local\Temp\ipykernel_22124\4202261298.py:4: RuntimeWarni
ng: divide by zero encountered in log10
y=np.log10(x)
No artists with labels found to put in legend. Note that artists whose label s
tart with an underscore are ignored when legend() is called with no argument.

Q3. Using Python, plot the graph of function f (x) = cos(x) on the interval [0, 2π].
In [6]:  from pylab import*
import numpy as np
x=np.linspace(0,2*pi,100)
f=np.cos(x)
plot(x,f,label="$\cos x$")

xlabel('x')
ylabel('y')

title('Graph of $\cos x$')
legend()
show()

Q4. Using Python, plot the graph of the function f (x) = arcsin(x) on the interval [−1, 1].
In [7]:  import matplotlib.pyplot as plt
import numpy as np
x=np.arange(-1,1,0.01)
y=np.arcsin(x)
plt.plot(x,y,'y')
plt.show

Out[7]: <function matplotlib.pyplot.show(close=None, block=None)>

Q5. Using Python, plot the graph of the function f (x) = sin(x) – e^x + 3x^2 − log10(x) on the
Interval [0, 2π].
In [8]:  import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,2*(np.pi),0.01)
y=np.sin(x)-np.exp(x)+3*x**2-np.log10(x)
plt.plot(x,y,'g')
plt.show

C:\Users\krush\AppData\Local\Temp\ipykernel_22124\2811857649.py:4: RuntimeWarni
ng: divide by zero encountered in log10
y=np.sin(x)-np.exp(x)+3*x**2-np.log10(x)

Out[8]: <function matplotlib.pyplot.show(close=None, block=None)>

Q6. Plot the graph of 𝑓(𝑥) = 𝑥^4 in [0, 5] with red dashed line with circle markers.
In [9]:  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')

title('Graph of $y=x^4$')
legend()
show()

Q7. Write a Python program to plot graph of the function f(x)=e^{-(x^2)} in [−5, 5] with green
dashed points line with upward pointing triangle.
In [10]:  from pylab import*
import numpy as np
x=np.linspace(-5,5,100)
y=np.exp(-(x**2))

plot(x,y,'-.^g',label="$y=e^{-x^2}$")
xlabel('x')
ylabel('y')

title('Graph of $y=e^{-x^2}$')
legend()
show()

Q8. Plot graph of y=e^{(x^2)} in [−5, 5] with red dashed-points line with upward pointing
triangle.
In [39]:  from pylab import*
import numpy as np
x=np.linspace(-5,5,100)
y=np.exp((x**2))

plot(x,y,'--^r',label="$y=e^{x^2}$")
xlabel('x')
ylabel('y')
grid(True)
title('Graph of $y=e^{x^2}$')
legend()
show()

Q9. Write a python program to plot the graph of 𝑦 = 𝑥^3 + 10𝑥 − 5, for 𝑥 ∈ [−10, 10] in red
colour..
In [12]:  from pylab import*
import numpy as np
x=np.linspace(-10,10,100)
y=(x**3)+(10*x)-5
plot(x,y,'r',label="$y=x^3+10x-5$")
xlabel('x')
ylabel('y')
grid(True)
title('Graph of $y=x^3+10x-5$')
legend()
show()

Q10. Write a Python program to plot the graph 2𝑥^2 − 4𝑥 + 5 in [– 10, 10] in magenta coloured
dashed pattern.
In [13]:  from pylab import*
import numpy as np
x=np.linspace(-10,10,100)
y=(2*x**2)-(4*x)-5
plot(x,y,'--m',label="$y=2x^2-4x+5$")
xlabel('x')
ylabel('y')
grid(True)
title('Graph of $y=2x^2-4x+5$')
legend()
show()

Q11. Write a Python program to plot graph of the function 𝑓(𝑥) = 𝑙𝑜𝑔(3𝑥^2), in [1, 10] with black
dashed points.
In [14]:  from pylab import*
import numpy as np
x=np.linspace(1,10,100)
y=np.log(3*x**2)
plot(x,y,'--k',label="$y=log(3x^2)$")
xlabel('x')
ylabel('y')
grid(True)
title('Graph of $y=log(3x^2)$')
legend()
show()

Q12. Write a python program to plot 2D graph of the functions 𝑓(𝑥) = 𝑙𝑜𝑔(𝑥) + 5 and 𝑔(𝑥) = 𝑙𝑜𝑔(𝑥)
− 5 in [0, 10] by setting different line width and different colors to the curve.
In [15]:  from pylab import*
import numpy as np
x=np.linspace(0,10,100)
f=np.log(x)+5
g=np.log(x)-5
plot(x,f,'r',label="$log(x)+5$",lw=0.8)
plot(x,g,'c',label="$log(x)-5$",lw=8)
xlabel('x')
ylabel('y')

title('Graph of log(x)+5 and log(x)-5')
legend()
show()

C:\Users\krush\AppData\Local\Temp\ipykernel_22124\3236577793.py:4: RuntimeWarni
ng: divide by zero encountered in log
f=np.log(x)+5
C:\Users\krush\AppData\Local\Temp\ipykernel_22124\3236577793.py:5: RuntimeWarni
ng: divide by zero encountered in log
g=np.log(x)-5

Q13. Write a Python program to plot 2D graph of the function 𝑓(𝑥) = 𝑠𝑖𝑛(𝑥) and 𝑔(𝑥) = 𝑐𝑜𝑠 𝑥 in
[−2𝜋, 2𝜋].
In [16]:  from pylab import*
import numpy as np
x=np.linspace(-2*pi,2*pi,100)
f=np.sin(x)
g=np.cos(x)
plot(x,f,label="$\sin x$",marker="o")
plot(x,g,label="$\cos x$",marker="+")
xlabel('x')
ylabel('y')

title('Graph of $\sin x$ and $\cos x$')
legend()
show()

Q14. Write a Python program to plot the 2D graph of the function 𝑓(𝑥) = (𝑒^𝑥)𝑠𝑖𝑛 𝑥 in [−5𝜋, 5𝜋]
with blue points line with upward pointing triangle.
In [17]:  from pylab import*
import numpy as np
x=np.linspace(-5*np.pi,5*np.pi,100)
y=np.exp(x)*np.sin(x)

plot(x,y,':^b',label="$y=e^{x}\sin(x)$")
xlabel('x')
ylabel('y')
grid(True)
title('Graph of $y=e^{x}\sin(x)$')
legend()
show()

Q15. Write a python program to draw 2D plot 𝑦 = 𝑥 𝑠𝑖𝑛 (1/x^2) in [−5, 5] with suitable label in the
x axis, y axis, a title and location of legend to lower right corner.
In [25]:  from pylab import*
import numpy as np
x=np.linspace(-5,5,100000)
y=x*np.sin(1/(x**2))
plot(x,y,'y',label="$y=xsin(\\frac{1}{x^2})$")
xlabel('x')
ylabel('y')
grid(True)
title('Graph of $y=xsin(\\frac{1}{x^2})$')
legend(loc=4)
show()

Q16.Write a python program plot the graphs of 𝑠𝑖𝑛 (𝑥) and 𝑐𝑜𝑠 (𝑥) in [0, 𝜋] in one figure with 2 × 1
subplots.
In [19]:  from pylab import*
import numpy as np
from math import*
x=np.linspace(0,np.pi,100)

y1=np.sin(x)
y2=np.cos(x)

subplot(2,1,1)
plot(x,y1,label="$\sin x$")
legend()

subplot(2,1,2)
plot(x,y2,label="$\cos x$")
legend()



show()

Q17. Plot the graphs of 𝑠𝑖𝑛 (𝑥), 𝑐𝑜𝑠 (𝑥), 𝑒^𝑥 and 𝑥^2 in [0, 5] in one figure with (2 × 2)
subplots.
In [20]:  from pylab import*
import numpy as np
from math import*
x=np.linspace(0,5,100)

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="$e^x$")
legend()

subplot(2,2,4)
plot(x,y4,label="$x^2$")
legend()

show()

Q.18. Write the Python program to plot the graph of the function, using def():𝑓(𝑥) = 𝑥^2 + 4 ; −10
≤ 𝑥 < 5, 𝑓(𝑥) = 3𝑥 + 9 ; 5 ≤ 𝑥 < 10
In [35]:  from pylab import*
import numpy as np
x1=np.linspace(-10,5,100)
x2=np.linspace(5,10,100)
y1=(x1**2)+4
y2=(3*x2)+9
plot(x1,y1,'blue')
plot(x2,y2,'blue')
xlabel('x')
ylabel('y')
grid(True)
title('Graph of $y=f(x)$')

show()

Q19. Write a python program to plot the graph of the following functions in the given
interval.

i) 𝑓(𝑥) = 𝑥^3 in [0, 5]. ii) 𝑓(𝑥) = 𝑥^2 in [−2, 2].


In [22]:  """i) 𝑓(𝑥) = 𝑥^3 in [0, 5]."""

from pylab import*
import numpy as np
x=np.linspace(0,5,100)
f=x**3

plot(x,f,'c',label="$f(x) = x^3$")
xlabel('x')
ylabel('y')

title('Graph of $f(x) = x^3$')
legend()
show()
In [29]:  """ii) 𝑓(𝑥) = 𝑥^2 in [−2, 2]."""
from pylab import*
import numpy as np
x=np.linspace(-2,2,100)
f=x**2

plot(x,f,'r',label="$f(x) = x^2$")

xlabel('x')
ylabel('y')

title('Graph of $f(x) = x^2$')
legend()
show()

Q20. Write a Python program to generate plot of the function 𝑓(𝑥) = 𝑥^2 in the interval [−5, 5], in
figure of size 6 × 6 inches
In [24]:  from pylab import*
import numpy as np
x=np.linspace(-2,2,100)
f=x**2
fig=plt.figure(figsize=(6,6))
plot(x,f,'m',label="$f(x) = x^2$")
grid(True)
xlabel('x')
ylabel('y')

title('Graph of $f(x) = x^2$')
legend()
show()
S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 2(Graph Plotting)
In [1]:  pip install pulp

Requirement already satisfied: pulp in c:\users\krush\anaconda3\lib\site-packages (2.8.0)


Note: you may need to restart the kernel to use updated packages.

In [2]:  pip install numpy

Requirement already satisfied: numpy in c:\users\krush\anaconda3\lib\site-packages (1.24.3)


Note: you may need to restart the kernel to use updated packages.

In [3]:  pip install matplotlib

Requirement already satisfied: matplotlib in c:\users\krush\anaconda3\lib\site-packages (3.7.1)


Requirement already satisfied: contourpy>=1.0.1 in c:\users\krush\anaconda3\lib\site-packages (f
rom matplotlib) (1.0.5)
Requirement already satisfied: cycler>=0.10 in c:\users\krush\anaconda3\lib\site-packages (from
matplotlib) (0.11.0)
Requirement already satisfied: fonttools>=4.22.0 in c:\users\krush\anaconda3\lib\site-packages
(from matplotlib) (4.25.0)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\users\krush\anaconda3\lib\site-packages
(from matplotlib) (1.4.4)
Requirement already satisfied: numpy>=1.20 in c:\users\krush\anaconda3\lib\site-packages (from m
atplotlib) (1.24.3)
Requirement already satisfied: packaging>=20.0 in c:\users\krush\anaconda3\lib\site-packages (fr
om matplotlib) (23.0)
Requirement already satisfied: pillow>=6.2.0 in c:\users\krush\anaconda3\lib\site-packages (from
matplotlib) (9.4.0)
Requirement already satisfied: pyparsing>=2.3.1 in c:\users\krush\anaconda3\lib\site-packages (f
rom matplotlib) (3.0.9)
Requirement already satisfied: python-dateutil>=2.7 in c:\users\krush\anaconda3\lib\site-package
s (from matplotlib) (2.8.2)
Requirement already satisfied: six>=1.5 in c:\users\krush\anaconda3\lib\site-packages (from pyth
on-dateutil>=2.7->matplotlib) (1.16.0)
Note: you may need to restart the kernel to use updated packages.

In [7]:  from mpl_toolkits import mplot3d


import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax=plt.axes(projection='3d')
Q1. Using python, generate 3D surface Plot for the function 𝑓(𝑥,y) = 𝑠𝑖𝑛(𝑥^2 + 𝑦^2) in the interval [0, 10].

In [5]:  # Import required libraries for plotting


from mpl_toolkits import mplot3d
import numpy as np
from pylab import*

# Define a function f(x, y) that returns the value of sin(x^2 + y^2)
def f(x, y):
return np.sin(x**2 + y**2)

# Generate linearly spaced values for x and y in the range [0, 10]
x = np.linspace(0, 10, 100)
y = np.linspace(0, 10, 100)

# Create a meshgrid from x and y values
X, Y = np.meshgrid(x, y)

# Evaluate the function f(x, y) at each point in the meshgrid
Z = f(X, Y)

# Create a 3D axis
ax = axes(projection='3d')

# Plot the 3D surface using the meshgrid and evaluated function values
ax.plot_surface(X, Y, Z, color='darkgreen')

# Set labels for the x and y axes
xlabel('x')
ylabel('y')

# Set the title of the plot
title('$𝑓(𝑥,𝑦) = 𝑠𝑖𝑛(𝑥^2 + 𝑦^2)$')

# Display the legend
#legend()

# Display the plot
show()

Q2. Write a Python program to generate 3D plot of the functions 𝑧 = sin (𝑥) + cos (𝑦) in −10 < 𝑥, 𝑦 < 10.
In [62]:  # Surface Plots

from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return np.sin(x)+np.cos(y)
x=np.linspace(-10,10,100)
y=np.linspace(-10,10,100)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.plot_surface(X,Y,Z,color='violet',edgecolor='none')

xlabel('x')
ylabel('y')

title('$𝑓(𝑥,y) = 𝑠𝑖𝑛(x)+cos(y))$')

legend()
show()

No artists with labels found to put in legend. Note that artists whose label start with an unde
rscore are ignored when legend() is called with no argument.
In [63]:  #Wireframe
from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return np.sin(x)+np.cos(y)
x=np.linspace(-10,10,100)
y=np.linspace(-10,10,100)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.plot_wireframe(X,Y,Z,rstride=3,cstride=3,color='orange')

xlabel('x')
ylabel('y')

title('$𝑓(𝑥,y) = 𝑠𝑖𝑛(x)+cos(y))$')

#legend()
show()
In [64]:  #Contour Plots
from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return np.sin(x)+np.cos(y)
x=np.linspace(-10,10,100)
y=np.linspace(-10,10,100)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.contour3D(X,Y,Z,50,cmap='plasma')#cmaps:viridis,plasma,inferno, magma,cividis

xlabel('x')
ylabel('y')

title('$𝑓(𝑥,y) = 𝑠𝑖𝑛(x)+cos(y))$')

#legend()
show()

Q3. Using Python plot the surface plot of parabola 𝑧 = 𝑥^2 + 𝑦^2 in −6 < 𝑥, 𝑦 < 6.
In [72]:  # Surface Plots

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,color='pink',edgecolor='black')

xlabel('x')
ylabel('y')

title('$𝑓(𝑥,y) = 𝑥^2 + 𝑦^2)$')

legend()
show()

No artists with labels found to put in legend. Note that artists whose label start with an unde
rscore are ignored when legend() is called with no argument.

Q4. Using python, generate 3D surface Plot for the function 𝑓(𝑥) = 𝑐𝑜𝑠(𝑥^2 + 𝑦^2 − 0.5) in the interval [0, 10].
In [40]:  # Surface Plots

from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return np.cos(x**2+y**2-0.5)
x=np.linspace(0,10,100)
y=np.linspace(0,10,100)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.plot_surface(X,Y,Z,color='olive')

xlabel('x')
ylabel('y')

title('$𝑓(𝑥,y) = 𝑐𝑜𝑠(𝑥^2 + 𝑦^2 − 0.5))$')

#legend()
show()

Q5. Write a python program to plot the 3D line graph whose parametric equation is (𝑐𝑜𝑠(2z), 𝑠𝑖𝑛(2z), z) for 10 ≤ z ≤ 20
(in red color), with title to the graph.
In [17]:  from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
import numpy as np
zvalue=np.linspace(10,20,100)
xvalue=np.sin(2*zvalue)
yvalue=np.cos(2*zvalue)
ax=plt.axes(projection='3d')
ax.plot3D(xvalue,yvalue,zvalue,':pr',label='3D Line',lw=1)
ax.legend()

Out[17]: <matplotlib.legend.Legend at 0x2606d360ed0>

Q6. Write a Python program to generate 3D plot of the functions z = sin⁡(x) + cos⁡(y) in -5 < x,y < 5.
In [99]:  # Surface Plots

from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return np.sin(x)+np.cos(x)
x=np.linspace(-5,5,100)
y=np.linspace(-5,5,100)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.plot_surface(X,Y,Z,color='mediumseagreen')

xlabel('x')
ylabel('y')

title('$𝑧 = sin (𝑥) + cos (𝑦)$')

#legend()
show()
In [24]:  #Wireframe
from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return np.sin(x)+np.cos(y)
x=np.linspace(-5,5,100)
y=np.linspace(-5,5,100)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.plot_wireframe(X,Y,Z,rstride=3,cstride=3,color='g')

xlabel('x')
ylabel('y')

title('$𝑓(𝑥,y) = 𝑠𝑖𝑛(x)+cos(y))$')

legend()
show()

No artists with labels found to put in legend. Note that artists whose label start with an unde
rscore are ignored when legend() is called with no argument.
In [101]:  # Contour
from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return np.sin(x)+np.cos(x)
x=np.linspace(-5,5,100)
y=np.linspace(-5,5,100)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.contour3D(X,Y,Z,50,cmap='cool')

xlabel('x')
ylabel('y')
title('$𝑧 = sin (𝑥) + cos (𝑦)$')

#legend()
show()

Q7. Write a Python program to plot graph of the function 𝑓(𝑥, 𝑦) = – 𝑥^2 − 𝑦^2 when −10 ≤ 𝑥, 𝑦 ≤ 10.
In [82]:  # Surface Plots

from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return -x**2-y**2
x=np.linspace(-10,10,100)
y=np.linspace(-10,10,100)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.plot_surface(X,Y,Z,cmap='seismic')

xlabel('x')
ylabel('y')

title('$𝑓(𝑥, 𝑦) = – 𝑥^2 − 𝑦^2$')

#legend()
show()
In [186]:  #Wireframe
from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return -x**2-y**2
x=np.linspace(-10,10,100)
y=np.linspace(-10,10,100)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.plot_wireframe(X,Y,Z,rstride=3,cstride=3,color='tab:purple')

xlabel('x')
ylabel('y')

title('$𝑓(𝑥, 𝑦) = – 𝑥^2 − 𝑦^2$')

#legend()
show()

Q8. Write a python program to plot the 3D graph of the function z = 𝑥^2 + 𝑦^2 in −6 < 𝑥, 𝑦 < 6 using surface plot.
In [172]:  # Surface Plots

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,40)
y=np.linspace(-6,6,40)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.plot_surface(X,Y,Z,cmap='Wistia',rstride=4,cstride=4,edgecolor='orange')

xlabel('x')
ylabel('y')

title('$𝑓(𝑥,y) = 𝑥^2 + 𝑦^2)$')

#legend()
show()

Q9. Write a python program to plot the 3D graph of the function z = 𝑥^2 + 𝑦^2 in −5 < 𝑥, 𝑦 < 5 using surface plot
In [184]:  # Surface Plots

from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return x**2+y**2
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_surface(X,Y,Z,rstride=2,cstride=2,color='aquamarine',edgecolor='navy')

xlabel('x')
ylabel('y')

title('$𝑓(𝑥,y) = 𝑥^2 + 𝑦^2)$')

legend()
show()

No artists with labels found to put in legend. Note that artists whose label start with an unde
rscore are ignored when legend() is called with no argument.

Q10. Write a python program to plot 3D contours for the function 𝑓(𝑥, 𝑦) = 𝑙𝑜𝑔(𝑥^2𝑦^2) when −5 ≤ 𝑥, 𝑦 ≤ 5, with
greens colour map.
In [2]:  from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return np.log((x**2)*(y**2))
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.contour3D(X,Y,Z,60,cmap='Greens')

xlabel('x')
ylabel('y')
title('$ 𝑓(𝑥, 𝑦) = 𝑙𝑜𝑔(𝑥^2𝑦^2)$')

#legend()
show()

Q11. Write a python program to plot 3D Surface Plot of the function 𝑧 = 𝑐𝑜𝑠(|𝑥| + |𝑦|) in −1 < 𝑥, 𝑦 < 1.
In [187]:  # Surface Plots

from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return np.cos(abs(x)+abs(y))
x=np.linspace(-1,1,100)
y=np.linspace(-1,1,100)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.plot_surface(X,Y,Z,cmap='hsv',edgecolor='none')

xlabel('x')
ylabel('y')

title('$z = 𝑐𝑜𝑠(|𝑥| + |𝑦|)$')

#legend()
show()

Q12. Write a Python program to plot the 3D graph of the function 𝑓(𝑥) = 𝑠𝑖𝑛( 𝑥^2 + 𝑦^2), −6 < 𝑥, 𝑦 < 6.
In [123]:  # Import required libraries for plotting
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, 100)
y = np.linspace(-6, 6, 100)


X, Y = np.meshgrid(x, y)
Z = f(X, Y)
ax = axes(projection='3d')
ax.plot_surface(X, Y, Z, cmap='PiYG')

# Set labels for the x and y axes
xlabel('x')
ylabel('y')

# Set the title of the plot
title('$𝑓(𝑥,𝑦) = 𝑠𝑖𝑛(\sqrt{x^2+y^2})$')

# Display the legend
#legend()

# Display the plot
show()

Q13. Write a Python program to plot the 3D graph of the function 𝑓(𝑥, 𝑦) = 𝑠𝑖𝑛 𝑥 + 𝑐𝑜𝑠 𝑦, 𝑥, 𝑦 ∈ [−2𝜋, 2𝜋] using
wireframe plot.
In [22]:  #Wireframe
from mpl_toolkits import mplot3d
import numpy as np
from pylab import*
def f(x,y):
return np.sin(x)+np.cos(y)
x=np.linspace(-np.pi,np.pi,100)
y=np.linspace(-np.pi,np.pi,100)

X,Y=np.meshgrid(x,y)
Z=f(X,Y)

ax=axes(projection='3d')
ax.plot_wireframe(X,Y,Z,rstride=3,cstride=3,color='coral')

xlabel('x')
ylabel('y')

title('$𝑓(𝑥, 𝑦) =𝑠𝑖𝑛(x)+cos(y)$')

#legend()
show()

Q14. Write a Python program to plot the 3D graph of the function 𝑓(𝑥) = 𝑒^((𝑥^2)+(𝑦^2)) for 𝑥, 𝑦 ∈ [0, 2𝜋] using
wireframe.
In [23]:  import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
def f(x,y):
return np.exp(x**2+y**2)
x=np.linspace(0,2*np.pi,100)
y=np.linspace(0,2*np.pi,100)
X,Y=np.meshgrid(x,y)
Z=f(X,Y)
fig=plt.figure()
ax=plt.axes(projection='3d')
ax.plot_wireframe(X,Y,Z,color='crimson',rstride=6,cstride=6)
ax.set_title('wireframe plot $𝑓(𝑥) = 𝑒^{𝑥^2+𝑦^2}$')

Out[23]: Text(0.5, 0.92, 'wireframe plot $𝑓(𝑥) = 𝑒^{𝑥^2+𝑦^2}$')

Q15. Using python, represent the following information using a bar graph (in green colour)

#Item Clothing Food Rent Petrol Miscellaneous



Expenditure (in Rs.) 600 4000 2000 1500 700
In [31]:  import matplotlib.pyplot as plt
left=[1,2,3,4,5]
height=[600,4000,2000,1500,700]
tick_label1=['Clothing','Food','Rent','Petrol','Miscellaneous']
plt.bar(left,height, tick_label=tick_label1,width= 0.8,color=['green'])
plt.xlabel('cities')
plt.ylabel('Expenditure (in Rs.)')
plt.title('Monthly Expenditure')
plt.show()

Q16. Using python, draw a bar graph in Green and Red colour to represent the data below:

Subject Maths Science English Marathi Hindi


% of Passing 68 90 70 85 91
In [35]:  import matplotlib.pyplot as plt
left=[1,2,3,4,5]
height=[68,90,70,85,91]
tick_label1=['Maths','Science','English','Marathi','Hindi']
plt.bar(left,height, tick_label=tick_label1,width= 0.6,color=['green','red'])
plt.xlabel('Subjects')
plt.ylabel('% of Passing')
plt.title('Give a suitable Title')
plt.show()

Q17. Following is the information of students participating in various games in a school. Represent it by a Bar
graph with bar width of 0.7 inches.


Game Cricket Football Hockey Chess Tennis
Number of Students 65 30 54 10 20
In [61]:  import matplotlib.pyplot as plt
left=[1,2,3,4,5]
height=[65,30,54,10,20]
tick_label1=['Cricket','Football','Hockey','Chess','Tennis']
plt.bar(left,height, tick_label=tick_label1,width= 0.7,color=['lightblue'],edgecolor='black',hatch
plt.xlabel('Games')
plt.ylabel('Number of Students')
plt.title('Bar Graph with Hatching')
plt.show()

Q18.Draw the horizontal bar graph for the following data in Maroon colour.


City Pune Mumbai Nasik Nagpur Thane
Air Quality Index 168 190 170 178 195
In [25]:  import matplotlib.pyplot as plt
left=[1,2,3,4,5]
height=[168,190,170,178,195]
tick_label1=['Pune','Mumbai','Nasik','Nagpur','Thane']
plt.barh(left,height, tick_label=tick_label1,height= 0.4,color=['maroon'],hatch='\+/',edgecolor='w
plt.xlabel('Cities')
plt.ylabel('Air Quality Index')
plt.title('Give a suitable Title')
plt.show()
S.Y.B.Sc. Comp. Sc. Sem-IV Practical no.
3(Application to Computational Geometry-I)
In [1]:  """The SymPy module allows us to create two-dimensional geometrical objects, such
and gives information about these objects like area of an ellipse, checking for c
finding the intersection between two lines. The primary use case of the module in
but it is possible to also use symbolic representations."""

Out[1]: 'The SymPy module allows us to create two-dimensional geometrical objects, such
as points, lines, polygons and circles, \nand gives information about these obj
ects like area of an ellipse, checking for collinearity of a set of points, or
\nfinding the intersection between two lines. The primary use case of the modul
e involves objects with numerical values, \nbut it is possible to also use symb
olic representations.'

In [2]:  pip install sympy

Requirement already satisfied: sympy in c:\users\krush\anaconda3\lib\site-packa


ges (1.11.1)Note: you may need to restart the kernel to use updated packages.

Requirement already satisfied: mpmath>=0.19 in c:\users\krush\anaconda3\lib\sit


e-packages (from sympy) (1.2.1)

Q1. Find the distance between points (i) 𝑥 and 𝑦 (ii) 𝑦 and 𝑤 (iii) 𝑥 and 𝑧, where 𝑥 = [0,0], 𝑦 = [2,2],
𝑧 = [−1, −1] and 𝑤 = [3,4]

In [3]:  from sympy import*


x = Point(0,0)
y = Point(2,2)
z = Point(-1,-1)
w = Point(3,4)
x.distance(y)

Out[3]: 2√⎯⎯2
In [4]:  y.distance(w)

Out[4]: √⎯⎯5
In [5]:  x.distance(z)

Out[5]: √⎯⎯2
Q2. Using sympy declare the points 𝐴 (0, 2), 𝐵 (5, 2), 𝐶 (3, 0) check whether these points are
collinear

In [6]:  from sympy import*


A = Point(0,2)
B = Point(5,2)
C = Point(3,0)
Point.is_collinear(A,B,C)

Out[6]: False
Q3. Using sympy declare the points 𝑃 (5, 2),𝑄 (-5, 2), 𝑅 (5, 0), check whether these points are
collinear.

In [40]:  """Refer previous problem and try it yourself"""

Out[40]: 'Refer previous problem and try it yourself'

Q4. Using sympy declare the points X (0,0,0),Y (2,2,2), Z (-1,-1,-1), W(3,4,-7), check whether these
points are coplanar.

In [8]:  from sympy import*


X = Point(0,0,0)
Y = Point(2,2,2)
Z = Point(-1,-1,-1)
W = Point(3,4,-7)
Point.are_coplanar(X,Y,Z,W)

Out[8]: True

Q5. Reflect the given points through respective lines.

(i) (3, 6) , 𝑥 + 𝑦 = 0

(ii) (2, 6), 2𝑥 + 𝑦 = −1

(iii) (0, −2), 𝑥 + 𝑦 = 5

(iv) (1.5, 3.6), 𝑥 − 2𝑦 = 1

In [9]:  """(i) (3, 6) , 𝑥 + 𝑦 = 0"""


x,y=symbols('x y')
P=Point(3,6)
P.reflect(Line(x+y))

Out[9]: Point2D(−6,−3)
In [26]:  """(ii) (2, 6) , 2𝑥 + 𝑦 = -1"""
x,y=symbols('x y')
Q=Point(2,6)
Q.reflect(Line(2*x+y+1))

Out[26]:
Point2D(− 345 , 85 )
In [11]:  """(iii) (0,-2) , 𝑥 + 𝑦 = 5"""
x,y=symbols('x y')
R=Point(0,-2)
R.reflect(Line(x+y-5))

Out[11]: Point2D(7,5)
In [12]:  """(iv) (1.5, 3.6) , 𝑥 - 2𝑦 = 1"""
x,y=symbols('x y')
S=Point(1.5,3.6)
S.reflect(Line(x-2*y-1))

Out[12]:
Point2D( 209 ,− 44
50 25 )
Q6.Reflect the point 𝑃[3,6] through the line 𝑥 − 2𝑦 + 4=0.

In [13]:  x,y=symbols('x y')


K=Point(3,6)
K.reflect(Line(x-2*y+4))

Out[13]: Point2D(5,2)
Q7. Consider the following entities:

(a) Line l passing through points (0,0) and (0,3)

(b) Segment s with endpoints (0,0) and (0,1)

(c) Ray r starting from (0,0) in the direction (8,8)

(i) Between each pair find the angle and minimum distance.

(ii) Also find midpoint and length of each entity.

(iii) Find minimum distance of each entity from the point P(10,3).

In [14]:  """Refer next problem and try it yourself"""

Out[14]: 'Refer next problem and try it yourself'

Q8. Consider the following entities:

(a) Line l passing through points (0,8) and (8,0)

(b) Segment s with endpoints (0,0) and (10,10)

(c) Ray r starting from (0,3) in the direction (3,0)

(i) Between each pair find the angle, intersection point.

(ii) Also find midpoint and length of each entity.

(iii) Find minimum distance of each entity from the point P(4,4).

In [27]:  l = Line((0,8),(8,0))
l

Out[27]: Line2D(Point2D(0,8),Point2D(8,0))
In [28]:  l.equation()

Out[28]: 8𝑥 + 8𝑦 − 64
In [16]:  s = Segment ((0,0),(10,10))
s

Out[16]: Segment2D(Point2D(0,0),Point2D(10,10))
In [17]:  r = Ray((0,3),(3,0))
r

Out[17]: Ray2D(Point2D(0,3),Point2D(3,0))
In [18]:  P = Point(4,4)
P

Out[18]: Point2D(4,4)
In [19]:  l.angle_between(s)

𝜋
Out[19]:
2
In [20]:  s.angle_between(r)

Out[20]: 𝜋
2
In [21]:  r.angle_between(l)

Out[21]: 0
In [22]:  l.intersection(s)

Out[22]: [Point2D(4, 4)]

In [23]:  s.intersection(r)

Out[23]: [Point2D(3/2, 3/2)]

In [24]:  r.intersection(l)

Out[24]: []

In [25]:  l.midpoint

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[25], line 1
----> 1 l.midpoint

AttributeError: 'Line2D' object has no attribute 'midpoint'

In [29]:  s.midpoint

Out[29]: Point2D(5,5)
In [30]:  r.midpoint()

---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[30], line 1
----> 1 r.midpoint()

AttributeError: 'Ray2D' object has no attribute 'midpoint'

In [31]:  l.length

Out[31]: ∞
In [32]:  s.length

Out[32]: 10√⎯⎯2
In [33]:  r.length

Out[33]: ∞
In [34]:  l.distance(P)

Out[34]: 0
In [35]:  s.distance(P)

Out[35]: 0
In [36]:  r.distance(P)

Out[36]: 5√⎯⎯2
2
Q9. Reflect the Line 4𝑥 + 3𝑦 = 5 through the line 𝑥 + 𝑦 = 0 and find the equation of the reflected
line.

In [37]:  from sympy import*


x,y=symbols('x,y')
L1=Line(4*x+3*y-5)
L2=Line(x+y-0)
#Reflection of Line L1 through L2
Line=L1.reflect(L2)
Line.equation()

Out[37]:
𝑥 + 4𝑦3 + 53
Q10.Reflect the line Ray having starting point (0,0) in the direction of (2,4) through line 𝑥 − 2𝑦 =
3.
In [38]:  from sympy import*
P=Point(0,0)
Q=Point(2,4)
R=Ray(P,Q)
x,y=symbols('x,y')
L=Line(x-2*y-3)
#Reflection of R through L
R.reflect(L)

Out[38]:
Ray2D(Point2D( 65 ,− 125 ),Point2D( 285 ,− 165 ))
Q11. Reflect the segment having endpoints (2,3) and (4,6) through line 7𝑥 + 6𝑦 = 3.

In [39]:  from sympy import*


P=Point(2,3)
Q=Point(4,6)
S=Segment(P,Q)
x,y=symbols('x,y')
L=Line(7*x+6*y-3)
#Reflection of S through L
S.reflect(L)

Out[39]:
Segment2D(Point2D(− 236 ,− 93 ,Point2D − 514 ,− 222
85 85 ) ( 85 85 ))
In [ ]:  ​
3/11/24, 9:40 AM S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 4 - Jupyter Notebook

S.Y.B.Sc. Comp. Sc. Sem-IV Practical no.


4(Application to Computational Geometry-
II)
In [1]: pip install sympy

Requirement already satisfied: sympy in c:\users\krush\anaconda3\lib\site


-packages (1.11.1)
Requirement already satisfied: mpmath>=0.19 in c:\users\krush\anaconda3\l
ib\site-packages (from sympy) (1.2.1)
Note: you may need to restart the kernel to use updated packages.

Q1. Using sympy declare the points P(5,2),Q(5,-2),R(5,0), check whether these points
are collinear. Declare the ray passing through the points P and Q, find the length of
this ray between P and Q. Also find slope of this ray.

In [2]: from sympy import*


P = Point(5,2)
Q = Point(-5,2)
R = Point(5,0)
Point.is_collinear(P,Q,R)

Out[2]: False

In [3]: R1=Ray(P,Q)
R1.length

Out[3]: ∞
In [4]: R1.slope

Out[4]: 0
Q2. Using sympy, declare the points A(0,7),B(5,2). Declare the line segment passing
through them. Find the length and midpoint of the line segment passing through
points A and B.

In [5]: from sympy import*


A = Point(0,7)
B = Point(5,2)
S=Segment(A,B)
S.length

Out[5]: 5√⎯⎯2
In [6]: S.midpoint

Out[6]:
Point2D( 52 , 92 )
localhost:8888/notebooks/Documents/S.Y.B.Sc. Sem-IV Practicals/Sem-IV Practicals 1 to 12/S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 4.ipynb 1/5
3/11/24, 9:40 AM S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 4 - Jupyter Notebook

Q3. Write a python program to rotate the segment by 180° having end points (1,0)
and (2,-1).

In [7]: from sympy import*


A = Point(1,0)
B = Point(2,-1)
S=Segment(A,B)
S.rotate(pi)

Out[7]: Segment2D(Point2D(−1,0),Point2D(−2,1))
Q4. Rotate the line by 30° degrees having two points (0,0) and (0,1) . Also find its
equation after applying rotation.

In [8]: from sympy import*


A = Point(0,0)
B = Point(0,1)
L=Line(A,B)
L1=L.rotate(pi/6)
L1.equation()

√ ⎯⎯3𝑥 𝑦
Out[8]:
− 2 −2
Q5. Write a python program to rotate the ray by 90° having starting point (1,0) and (2,
−1).

In [9]: from sympy import*


A = Point(1,0)
B = Point(2,-1)
R=Ray(A,B)
R.rotate(pi/2)

Out[9]: Ray2D(Point2D(0,1),Point2D(1,2))
Q6. Using python, rotate the line segment by 180° having end points (1,4) and
(2,-1)

In [10]: from sympy import*


A = Point(1,4)
B = Point(2,-1)
S=Segment(A,B)
S.rotate(pi)

Out[10]: Segment2D(Point2D(−1,−4),Point2D(−2,1))
Q7. Write a python program to apply the following transformations on the point (-2,4)
:

(i) Shearing in Y direction by 7 units.

localhost:8888/notebooks/Documents/S.Y.B.Sc. Sem-IV Practicals/Sem-IV Practicals 1 to 12/S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 4.ipynb 2/5
3/11/24, 9:40 AM S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 4 - Jupyter Notebook

(ii) Shearing in X and Y direction by 4 and 7 units respectively.

(iii) Rotation about origin by an angle 60°.

(iv) Rotation about origin by an angle 48°.

(v) Scaling in X and Y direction by 7/2 and 4 units respectively.

(vi) Reflection through the line y=2x+3.

(vii) Reflection through the line 3x+4y=5


In [43]: from sympy import*
#(i)
K=Point(-2,4)
K

Out[43]: Point2D(−2,4)
In [48]: M1=Matrix([[1,7,0],[0,1,0],[0,0,1]])
M1

 1 7 0
Out[48]:
 0 1 0 
 0 0 1
In [49]: K.transform(M1)

Out[49]: Point2D(−2,−10)
In [53]: #(ii)

M2=Matrix([[1,7,0],[4,1,0],[0,0,1]])
M2

 1 7 0
Out[53]:
 4 1 0 
 0 0 1
In [54]: K.transform(M2)

Out[54]: Point2D(14,−10)
In [13]: #(iii)
from math import*
angle=radians(60)
K.rotate(angle)

Out[13]:
Point2D(− 17856406460551 , 267949192431123
4000000000000 1000000000000000 )

localhost:8888/notebooks/Documents/S.Y.B.Sc. Sem-IV Practicals/Sem-IV Practicals 1 to 12/S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 4.ipynb 3/5
3/11/24, 9:40 AM S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 4 - Jupyter Notebook

In [14]: #(iv)
from math import*
angle=radians(48)
K.rotate(angle)

Out[14]:
Point2D(− 431084051462729 , 929869355063
100000000000000 781250000000 )
In [15]: #(v) Method 1
K.scale(7/2,4)

Out[15]: Point2D(−7,16)
In [16]: #(v) Method 2
K.transform(Matrix([[7/2,0,0],[0,4,0],[0,0,1]]))

Out[16]: Point2D(−7,16)
In [17]: #(vi)

x,y=symbols('x y')
K.reflect(Line(2*x-y+3))

Out[17]: Point2D(2,2)
In [18]: #(vii)
x,y=symbols('x y')
K.reflect(Line(3*x+4*y-5))

Out[18]:
Point2D(− 165 , 125 )
In [19]: """Refer Q7. and try it yourself"""

Out[19]: 'Refer Q7. and try it yourself'

Q8. Write a python program to apply the following transformations on the point
P[4,3] :

(i) Reflection through X−axis.

(ii) Scaling in X−coordinate by factor 2.

(iii) Scaling in Y−coordinate by factor 1.5.

(iv) Reflection through the line y = x.

In [20]: """Refer Q7. and try it yourself"""

Out[20]: 'Refer Q7. and try it yourself'

Q9. Apply each of the following transformations on the point P [3,-1].

(i) Reflection through Y-axis.

localhost:8888/notebooks/Documents/S.Y.B.Sc. Sem-IV Practicals/Sem-IV Practicals 1 to 12/S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 4.ipynb 4/5
3/11/24, 9:40 AM S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 4 - Jupyter Notebook

(ii) Scaling in X and Y direction by 1/2 and 3 units respectively.

(iii) Shearing in both X and Y direction by -2 and 4 units respectively.

(iv) Rotation about origin by an angle 60 degrees.

In [21]: """Refer Q7. and try it yourself"""

Out[21]: 'Refer Q7. and try it yourself'

localhost:8888/notebooks/Documents/S.Y.B.Sc. Sem-IV Practicals/Sem-IV Practicals 1 to 12/S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 4.ipynb 5/5
S.Y.B.Sc. Comp. Sc. Sem-IV Practical no.
5(Application to Computational Geometry-III)
In [1]: pip install sympy

Requirement already satisfied: sympy in c:\users\krush\anaconda3\lib\site-packages


(1.11.1)
Requirement already satisfied: mpmath>=0.19 in c:\users\krush\anaconda3\lib\site-pa
ckages (from sympy) (1.2.1)
Note: you may need to restart the kernel to use updated packages.

Q1. Write a python program to plot the Triangle with vertices at [4,3], [6,3], [6,5]. and its
reflections through, (i) x-axis, (ii) y-axis. All the figures must be in different colours, also plot the
two axes.
In [11]: import matplotlib.pyplot as plt
import numpy as np

def plot_triangle(vertices, color, label):
# Function to plot a triangle
triangle = plt.Polygon(vertices, closed=True, edgecolor=color, facecolor='none',
plt.gca().add_patch(triangle)# gca(get current axes):used to add the created poly
# Displaying coordinates next to each vertex
for vertex in vertices:
plt.text(vertex[0], vertex[1], f'({vertex[0]}, {vertex[1]})', fontsize=8, ha=

# Original Triangle
original_triangle = np.array([[4, 3], [6, 3], [6, 5]])

# Reflection through x-axis
reflected_x_axis = np.array([[4, -3], [6, -3], [6, -5]])

# Reflection through y-axis
reflected_y_axis = np.array([[-4, 3], [-6, 3], [-6, 5]])

# Plotting
plt.axhline(0, color='black', linewidth=1) # x-axis
plt.axvline(0, color='black', linewidth=1) # y-axis

# Plot the original triangle
plot_triangle(original_triangle, color='blue', label='Original Triangle')

# Plot the reflection through x-axis
plot_triangle(reflected_x_axis, color='green', label='Reflection through x-axis')

# Plot the reflection through y-axis
plot_triangle(reflected_y_axis, color='red', label='Reflection through y-axis')

# Add legend and labels
plt.legend()
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Reflections of a Triangle')

# Add grid
plt.grid(True, linestyle='--', alpha=0.5)

# Set plot limits
plt.xlim(-8, 8)
plt.ylim(-8, 8)

# Display the plot
plt.show()
Q2. Write a python program to plot the Triangle with vertices at [3,3],[3,6],[0,6] and its reflections
through, line y = x and Y-axis. Also plot the mirror lines.
In [5]: #Method 1
import matplotlib.pyplot as plt
import numpy as np

def plot_triangle(vertices, color, label):
# Function to plot a triangle
triangle = plt.Polygon(vertices, closed=True, edgecolor=color, facecolor='none',
plt.gca().add_patch(triangle) # gca(get current axes):used to add the created po
# Displaying coordinates next to each vertex
for vertex in vertices:
plt.text(vertex[0], vertex[1], f'({vertex[0]}, {vertex[1]})', fontsize=8, ha=

# Original Triangle
original_triangle = np.array([[3, 3], [3, 6], [0, 6]])

# Reflection through y-axis
reflected_y_axis = np.array([[-3, 3], [-3, 6], [-0, 6]])

# Reflection through y=x
reflected_y_equals_x = np.array([[3, 3], [6, 3], [6, 0]])

# Plotting
plt.axhline(0, color='black', linewidth=1) # x-axis
plt.axvline(0, color='black', linewidth=1) # y-axis

# Plot the original triangle
plot_triangle(original_triangle, color='blue', label='Original Triangle')


# Plot the reflection through y-axis
plot_triangle(reflected_y_axis, color='red', label='Reflection through y-axis')

# Plot the reflection through y=x
plot_triangle(reflected_y_equals_x, color='purple', label='Reflection through y=x')

# Plot the y=x line
plt.plot([-8, 8], [-8, 8], color='green', linestyle='--', label='y=x')

# Add legend and labels
plt.legend()
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Reflections of a Triangle')

# Add grid
plt.grid(True, linestyle='--', alpha=1)

# Set plot limits
plt.xlim(-8, 8)
plt.ylim(-8, 8)

# Display the plot
plt.show()
In [ ]: ​

Q3. Write a python program to Plot 2D x-axis and y-axis in black colour. In the same diagram
plot:

(i) Green triangle with vertices [5,4],[7,4],[6,6].

(ii) Blue rectangle with vertices [2,2],[10,2],[10,8],[2,8].

(iii) Red polygon with vertices [6,2],[10,4],[8,7],[4,8],[2,4].

(iv) Isosceles triangle with vertices [0,0],[4,0],[2,4].


In [8]: import matplotlib.pyplot as plt
import matplotlib.patches as patches

# Function to plot a polygon with specified vertices and color
def plot_polygon(vertices, color):
polygon = plt.Polygon(vertices, closed=True, edgecolor=color, facecolor='none')
plt.gca().add_patch(polygon)

# Displaying coordinates next to each vertex
for vertex in vertices:
plt.text(vertex[0], vertex[1], f'({vertex[0]}, {vertex[1]})', fontsize=8, ha=
"""vertex[0] and vertex[1] are the x and y coordinates of the current vertex
f'({vertex[0]}, {vertex[1]})': This is an f-string that formats the text to be displa
fontsize=8: Sets the font size of the text to 8.
ha='right': Horizontal alignment is set to 'right', which means the text is aligned t
va='bottom': Vertical alignment is set to 'bottom', which means the text is aligned t

# Plotting the x-axis and y-axis in black
plt.axhline(0, color='black', linewidth=1)
plt.axvline(0, color='black', linewidth=1)

# (i) Green triangle with vertices [5,4],[7,4],[6,6]
green_triangle = [[5, 4], [7, 4], [6, 6]]
plot_polygon(green_triangle, 'green')

# (ii) Blue rectangle with vertices [2,2],[10,2],[10,8],[2,8]
blue_rectangle = [[2, 2], [10, 2], [10, 8], [2, 8]]
plot_polygon(blue_rectangle, 'blue')

# (iii) Red polygon with vertices [6,2],[10,4],[8,7],[4,8],[2,4]
red_polygon = [[6, 2], [10, 4], [8, 7], [4, 8], [2, 4]]
plot_polygon(red_polygon, 'red')

# (iv) Isosceles triangle with vertices [0,0],[4,0],[2,4]
isosceles_triangle = [[0, 0], [4, 0], [2, 4]]
plot_polygon(isosceles_triangle, 'purple')

# Adding grids
plt.grid(True, linestyle='--', alpha=1)

# Adding axis titles
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Setting plot limits
plt.xlim(-1, 12)
plt.ylim(-1, 10)

# Display the plot
plt.show()
Q4. Write a Python program to draw a polygon with vertices (0,0), (2,0), (2,3) and (1,6) and rotate
180°. Also find internal angles at each point.

In [1]: from sympy import*


x,y=symbols('x,y')
P=Point(0,0)
Q=Point(2,0)
R=Point(2,3)
S=Point(1,6)
Poly=Polygon(P,Q,R,S)
Poly

Out[1]: Polygon(Point2D(0,0),Point2D(2,0),Point2D(2,3),Point2D(1,6))
In [15]: P.rotate(pi)

Out[15]: Polygon(Point2D(0,0),Point2D(−2,0),Point2D(−2,−3),Point2D(−1,−6))
Q5. Write a Python program to find the area and perimeter of the ∆ABC, where A[0,0], B[5,0],
C[3,3]. Also find angle at each vertex.

In [3]: from sympy import*


x,y=symbols('x,y')
A=Point(0,0)
B=Point(5,0)
C=Point(3,3)
T=Triangle(A,B,C)
T.area

Out[3]: 15
2
In [4]: T.perimeter

Out[4]: √⎯13⎯⎯⎯ + 3√⎯⎯2 + 5


In [5]: T.angles[A]

𝜋
4
Out[5]:

In [6]: T.angles[B]

2 √ ⎯13⎯⎯⎯
acos ( 13 )
Out[6]:

In [7]: T.angles[C]

√ ⎯26⎯⎯⎯
acos ( 26 )
Out[7]:

Q6. Using python, drawn a regular polygon with 6 sides and radius 1 centred at (1,2) and find its
area and perimeter.

In [30]: P=Polygon((1,2),1,n=6) # Creates a 6-sided polygon with centre at point (1,2) with ra
P

Out[30]: RegularPolygon(Point2D(1,2),1,6,0)
In [32]: P.area

Out[32]: 3√⎯⎯3
2
In [33]: P.perimeter

Out[33]: 6
Q7. Write a Python program to find the area and perimeter of the ∆ABC, where A[0,0], B[6,0],
C[4,4]. Also find angle at each vertex.

In [ ]: """Refer Q5. and try it yourself"""

Q8. Write a python program to reflect the ∆ABC through the line y = 3 where A(1,0), B(2,-1),
C(-1,3).
In [17]: from sympy import*
x,y=symbols('x,y')
A=Point(1,0)
B=Point(2,-1)
C=Point(-1,3)
T=Triangle(A,B,C)
T

Out[17]: Triangle(Point2D(1,0),Point2D(2,−1),Point2D(−1,3))
In [21]: P=Point(0,3)
Q=Point(1,3)
L=Line(P,Q)
L.equation()

Out[21]: 𝑦−3
In [22]: T.reflect(L) #Reflects Triangle T about Line L

Out[22]: Triangle(Point2D(1,6),Point2D(2,7),Point2D(−1,3))
Q9. Generate triangle with vertices (0,0), (4,0), (1,4), check whether the triangle is Scalene
triangle.

In [24]: T=Triangle(Point(0,0),Point(4,0),Point(1,4))
T.is_scalene()

Out[24]: True

Q10. Rotate the line segment by -π radians having end points (1,0) and (2,-1).

In [ ]: """Refer Q3. of practical no. 4 and try it yourself"""

Q11. Write a Python program to draw regular polygon with 20 sides and radius 1 centred at
(0,0).

In [ ]: """Refer Q6. and try it yourself"""

Q12. Using python, generate triangle with vertices (0,0), (4,0), (2,4), check whether the triangle is
isosceles triangle.

In [27]: T1=Triangle(Point(0,0),Point(4,0),Point(2,4))
T1.is_isosceles()

Out[27]: True
S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 6(Study of
Graphical aspects of Two-dimensional
transformation matrix using matplotlib)
In [1]: pip install sympy

Requirement already satisfied: sympy in c:\users\krush\anaconda3\lib\site-packages


(1.11.1)Note: you may need to restart the kernel to use updated packages.

Requirement already satisfied: mpmath>=0.19 in c:\users\krush\anaconda3\lib\site-pa


ckages (from sympy) (1.2.1)

Q1. If the line with points A[2,1],B[4,-1] is transformed by the transformation matrix [T]=[(1,2),
(2,1)] then using python, find the equation of transformed line.

In [40]: from sympy import*


A = Point(2,1)
B = Point(4,-1)
M= Matrix([[1,2,0],[2,1,0],[0,0,1]])
M

 1 2 0
Out[40]:
 2 1 0 
 0 0 1
In [41]: A1=A.transform(M)

In [42]: A1

Out[42]: Point2D(4,5)
In [44]: B1=B.transform(M)
B1

Out[44]: Point2D(2,7)
In [45]: L=Line(A1,B1)
L

Out[45]: Line2D(Point2D(4,5),Point2D(2,7))
In [46]: L.equation()

Out[46]: −2𝑥 − 2𝑦 + 18
Q2. If the line with points A[3,1],B[5,-1] is transformed by the transformation matrix [T]=[(3,-2),
(2,1)] then using python, find the equation of transformed line.
In [7]: from sympy import*
A = Point(3,1)
B = Point(5,-1)

M=Matrix([[3,-2,0],[2,1,0],[0,0,1]])
M

 3 −2 0 
Out[7]:
 2 1 0 
0 0 1
In [8]: A1=A.transform(M)
B1=B.transform(M)

In [9]: A1

Out[9]: Point2D(11,−5)
In [10]: B1

Out[10]: Point2D(13,−11)
In [11]: L=Line(A1,B1)
L

Out[11]: Line2D(Point2D(11,−5),Point2D(13,−11))
In [12]: L.equation()

Out[12]: 6𝑥 + 2𝑦 − 56
Q3. If the line segment joining the points A[2,5] and B[4,-13] is transformed to the line segment
A'B' by the transformation matrix [T]=[[2,3],[4,1)] , then using python find the slope and midpoint
of the transformed line

In [13]: from sympy import*


A = Point(2,5)
B = Point(4,-13)
M=Matrix([[2,3,0],[4,1,0],[0,0,1]])

B1=B.transform(Matrix([[3,-2,0],[2,1,0],[0,0,1]]))
M

 2 3 0
Out[13]:
 4 1 0 
 0 0 1
In [14]: A1=A.transform(M)
A1

Out[14]: Point2D(24,11)
In [15]: A1

Out[15]: Point2D(24,11)
In [20]: B1=B.transform(M)
B1

Out[20]: Point2D(−44,−1)
In [21]: S=Segment(A1,B1)
S

Out[21]: Segment2D(Point2D(24,11),Point2D(−44,−1))
In [22]: S.slope

Out[22]: 3
17
In [23]: S.midpoint

Out[23]: Point2D(−10,5)
Q4. Write a Python program to find the equation of the transformed line if shearing is applied on
the line 2x + y = 3 in x and y direction by 2 and -3 units respectively.

In [24]: """Refer Q3. and try it yourself using Shearing matrix"""

Out[24]: 'Refer Q3. and try it yourself using Shearing matrix'

Q5. Write a python program to plot square with vertices at [4,4],[2,4],[2,2],[4,2] and find its
uniform expansion by factor 3, uniform reduction by factor 0.4.
In [25]: import matplotlib.pyplot as plt
import numpy as np

def plot_square(vertices, color, label):
square = plt.Polygon(vertices, closed=True, edgecolor=color, facecolor=color, lab
plt.gca().add_patch(square)
# Displaying coordinates next to each vertex
for vertex in vertices:
plt.text(vertex[0], vertex[1], f'({vertex[0]}, {vertex[1]})', fontsize=9, ha=

# Original Square
original_square = np.array([[4, 4], [2, 4], [2, 2], [4, 2]])

# Calculate the uniform expansion and reduction factors
expansion_factor = 3
reduction_factor = 0.4

# Uniformly expand the original square by the factor
expanded_square = original_square * expansion_factor

# Uniformly reduce the original square by the factor
reduced_square = original_square * reduction_factor

# Plotting
plt.axhline(0, color='black', linewidth=1) # x-axis
plt.axvline(0, color='black', linewidth=1) # y-axis

# Plot the original filled square
plot_square(original_square, color='blue', label='Original Square')

# Plot the filled expanded square
plot_square(expanded_square, color='green', label='Expanded Square (3x)')

# Plot the filled reduced square
plot_square(reduced_square, color='red', label='Reduced Square (0.4x)')

# Add legend and labels
plt.legend()
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Uniform Expansion and Reduction of a Square')

# Add grid
plt.grid(True, linestyle='--', alpha=0.5)

# Set plot limits
plt.xlim(0, 15)
plt.ylim(0, 15)

# Display the plot
plt.show()
Q6. Write a Python program to plot the rectangle with vertices at [2,1],[2,4],[5,4],[5,1], and its
uniform expansion by factor 4.
In [ ]: import matplotlib.pyplot as plt
import numpy as np

def plot_rectangle(vertices, color, label):
rectangle = plt.Polygon(vertices, closed=True, edgecolor=color, facecolor=color,
plt.gca().add_patch(rectangle)
# Displaying coordinates next to each vertex
for vertex in vertices:
plt.text(vertex[0], vertex[1], f'({vertex[0]}, {vertex[1]})', fontsize=8, ha=

# Original Rectangle
original_rectangle = np.array([[2, 1], [2, 4], [5, 4], [5, 1]])

# Calculate the uniform expansion factor
expansion_factor = 4

# Uniformly expand the original rectangle by the factor
expanded_rectangle = original_rectangle * expansion_factor

# Plotting
plt.axhline(0, color='black', linewidth=1) # x-axis
plt.axvline(0, color='black', linewidth=1) # y-axis

# Plot the original filled rectangle
plot_rectangle(original_rectangle, color='blue', label='Original Rectangle')

# Plot the filled expanded rectangle
plot_rectangle(expanded_rectangle, color='green', label='Expanded Rectangle')

# Add legend and labels
plt.legend()
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Uniform Expansion of a Rectangle')

# Add grid
plt.grid(True, linestyle='--', alpha=0.5)

# Set plot limits
plt.xlim(0, 25)
plt.ylim(0, 25)

# Display the plot
plt.show()

Q7.If two lines 2x- y = 5 and x + 3y = -3 are transformed using the transformation matrix [T]=
[(-2,3),(1,1)]. Then find the point of intersection of the transformed lines.

In [26]: from sympy import*


x,y=symbols('x,y')
l1=Line(2*x - y - 5)
l2=Line(x + 3*y + 1)
P=l1.intersection(l2) # Intersection point of l1 and l2 in list form
P

Out[26]: [Point2D(2, -1)]

In [27]: P1=P[0] # Intersection point in the point form is the 1st element in the list
P1

Out[27]: Point2D(2,−1)
In [28]: P2=P1.transform(Matrix([[-2,3,0],[1,1,0],[0,0,1]])) # Transformed Intersection point
P2

Out[28]: Point2D(−5,5)
Q8. If a 2×2 matrix [T]=[(1,3),(-2,2)] is used to transform the line L, then the equation of the
transformed line is y*=x*+4. Find the equation of the original line.

In [29]: x,y=symbols('x,y')
l=Line(x-y+4) # equation of the transformed line
l

Out[29]: Line2D(Point2D(0,4),Point2D(1,5))
In [30]: l.equation()

Out[30]: −𝑥 + 𝑦 − 4
In [31]: lpoints=l.points #takes two points on l in a list form
lpoints

Out[31]: (Point2D(0, 4), Point2D(1, 5))

In [32]: p=lpoints[0]
p

Out[32]: Point2D(0,4)
In [33]: q=lpoints[1]
q

Out[33]: Point2D(1,5)
In [34]: M=Matrix([[1,3,0],[-2,2,0],[0,0,1]]) # Transformation matrix
M

 1 3 0
Out[34]:
 −2 2 0 
 0 0 1
In [35]: N=M.inv()
N

Out[35]:  14 − 38 0 
 14 18 0 
 0 0 1
In [36]: p1=p.transform(N)
p1

Out[36]:
Point2D(1, 12 )
In [37]: q1=q.transform(N)
q1

Out[37]:
Point2D( 32 , 14 )
In [38]: L=Line(p1,q1) # Required line
L

Out[38]:
Line2D(Point2D(1, 12 ),Point2D( 32 , 14 ))
In [39]: L.equation()

Out[39]: 𝑥+𝑦−1
4 2 2
In [ ]: ​
S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 7(Study of
Graphical aspects of Three-dimensional
transformation matrix using matplotlib-I)
In [1]: pip install sympy

Requirement already satisfied: sympy in c:\users\krush\anaconda3\lib\site-packages


(1.11.1)
Requirement already satisfied: mpmath>=0.19 in c:\users\krush\anaconda3\lib\site-pa
ckages (from sympy) (1.2.1)
Note: you may need to restart the kernel to use updated packages.

In [7]: import numpy as np



x = np.linspace(-1, 1, 10)
print(x)

for i in range(len(x) - 1):
print(f"Subinterval {i + 1}: ({x[i]}, {x[i + 1]})")

[-1. -0.77777778 -0.55555556 -0.33333333 -0.11111111 0.11111111


0.33333333 0.55555556 0.77777778 1. ]
Subinterval 1: (-1.0, -0.7777777777777778)
Subinterval 2: (-0.7777777777777778, -0.5555555555555556)
Subinterval 3: (-0.5555555555555556, -0.33333333333333337)
Subinterval 4: (-0.33333333333333337, -0.11111111111111116)
Subinterval 5: (-0.11111111111111116, 0.11111111111111116)
Subinterval 6: (0.11111111111111116, 0.33333333333333326)
Subinterval 7: (0.33333333333333326, 0.5555555555555554)
Subinterval 8: (0.5555555555555554, 0.7777777777777777)
Subinterval 9: (0.7777777777777777, 1.0)

In [4]: import numpy as np



x = np.linspace(-1, 1, 10+1)
print(x)

for i in range(len(x) - 1):
print(f"Subinterval {i + 1}: ({x[i]}, {x[i + 1]})")

[-1. -0.8 -0.6 -0.4 -0.2 0. 0.2 0.4 0.6 0.8 1. ]


Subinterval 1: (-1.0, -0.8)
Subinterval 2: (-0.8, -0.6)
Subinterval 3: (-0.6, -0.3999999999999999)
Subinterval 4: (-0.3999999999999999, -0.19999999999999996)
Subinterval 5: (-0.19999999999999996, 0.0)
Subinterval 6: (0.0, 0.20000000000000018)
Subinterval 7: (0.20000000000000018, 0.40000000000000013)
Subinterval 8: (0.40000000000000013, 0.6000000000000001)
Subinterval 9: (0.6000000000000001, 0.8)
Subinterval 10: (0.8, 1.0)

Q1. Write a Python program to generate vector x in the interval [-22,22] using numpy package
with 80 subintervals.
In [25]: import numpy as np

x = np.linspace(-22, 22, 80+1)
print(x)

for i in range(len(x) - 1):
print(f"Subinterval {i + 1}: ({x[i]}, {x[i + 1]})")
[-22. -21.45 -20.9 -20.35 -19.8 -19.25 -18.7 -18.15 -17.6 -17.05
-16.5 -15.95 -15.4 -14.85 -14.3 -13.75 -13.2 -12.65 -12.1 -11.55
-11. -10.45 -9.9 -9.35 -8.8 -8.25 -7.7 -7.15 -6.6 -6.05
-5.5 -4.95 -4.4 -3.85 -3.3 -2.75 -2.2 -1.65 -1.1 -0.55
0. 0.55 1.1 1.65 2.2 2.75 3.3 3.85 4.4 4.95
5.5 6.05 6.6 7.15 7.7 8.25 8.8 9.35 9.9 10.45
11. 11.55 12.1 12.65 13.2 13.75 14.3 14.85 15.4 15.95
16.5 17.05 17.6 18.15 18.7 19.25 19.8 20.35 20.9 21.45
22. ]
Subinterval 1: (-22.0, -21.45)
Subinterval 2: (-21.45, -20.9)
Subinterval 3: (-20.9, -20.35)
Subinterval 4: (-20.35, -19.8)
Subinterval 5: (-19.8, -19.25)
Subinterval 6: (-19.25, -18.7)
Subinterval 7: (-18.7, -18.15)
Subinterval 8: (-18.15, -17.6)
Subinterval 9: (-17.6, -17.05)
Subinterval 10: (-17.05, -16.5)
Subinterval 11: (-16.5, -15.95)
Subinterval 12: (-15.95, -15.399999999999999)
Subinterval 13: (-15.399999999999999, -14.85)
Subinterval 14: (-14.85, -14.299999999999999)
Subinterval 15: (-14.299999999999999, -13.75)
Subinterval 16: (-13.75, -13.2)
Subinterval 17: (-13.2, -12.649999999999999)
Subinterval 18: (-12.649999999999999, -12.1)
Subinterval 19: (-12.1, -11.549999999999999)
Subinterval 20: (-11.549999999999999, -11.0)
Subinterval 21: (-11.0, -10.45)
Subinterval 22: (-10.45, -9.899999999999999)
Subinterval 23: (-9.899999999999999, -9.35)
Subinterval 24: (-9.35, -8.799999999999999)
Subinterval 25: (-8.799999999999999, -8.249999999999998)
Subinterval 26: (-8.249999999999998, -7.699999999999999)
Subinterval 27: (-7.699999999999999, -7.149999999999999)
Subinterval 28: (-7.149999999999999, -6.599999999999998)
Subinterval 29: (-6.599999999999998, -6.049999999999999)
Subinterval 30: (-6.049999999999999, -5.5)
Subinterval 31: (-5.5, -4.949999999999999)
Subinterval 32: (-4.949999999999999, -4.399999999999999)
Subinterval 33: (-4.399999999999999, -3.849999999999998)
Subinterval 34: (-3.849999999999998, -3.299999999999997)
Subinterval 35: (-3.299999999999997, -2.75)
Subinterval 36: (-2.75, -2.1999999999999993)
Subinterval 37: (-2.1999999999999993, -1.6499999999999986)
Subinterval 38: (-1.6499999999999986, -1.0999999999999979)
Subinterval 39: (-1.0999999999999979, -0.5499999999999972)
Subinterval 40: (-0.5499999999999972, 0.0)
Subinterval 41: (0.0, 0.5500000000000007)
Subinterval 42: (0.5500000000000007, 1.1000000000000014)
Subinterval 43: (1.1000000000000014, 1.6500000000000021)
Subinterval 44: (1.6500000000000021, 2.200000000000003)
Subinterval 45: (2.200000000000003, 2.7500000000000036)
Subinterval 46: (2.7500000000000036, 3.3000000000000007)
Subinterval 47: (3.3000000000000007, 3.8500000000000014)
Subinterval 48: (3.8500000000000014, 4.400000000000002)
Subinterval 49: (4.400000000000002, 4.950000000000003)
Subinterval 50: (4.950000000000003, 5.5000000000000036)
Subinterval 51: (5.5000000000000036, 6.050000000000001)
Subinterval 52: (6.050000000000001, 6.600000000000001)
Subinterval 53: (6.600000000000001, 7.150000000000002)
Subinterval 54: (7.150000000000002, 7.700000000000003)
Subinterval 55: (7.700000000000003, 8.250000000000004)
Subinterval 56: (8.250000000000004, 8.800000000000004)
Subinterval 57: (8.800000000000004, 9.350000000000001)
Subinterval 58: (9.350000000000001, 9.900000000000002)
Subinterval 59: (9.900000000000002, 10.450000000000003)
Subinterval 60: (10.450000000000003, 11.0)
Subinterval 61: (11.0, 11.550000000000004)
Subinterval 62: (11.550000000000004, 12.100000000000001)
Subinterval 63: (12.100000000000001, 12.650000000000006)
Subinterval 64: (12.650000000000006, 13.200000000000003)
Subinterval 65: (13.200000000000003, 13.75)
Subinterval 66: (13.75, 14.300000000000004)
Subinterval 67: (14.300000000000004, 14.850000000000001)
Subinterval 68: (14.850000000000001, 15.400000000000006)
Subinterval 69: (15.400000000000006, 15.950000000000003)
Subinterval 70: (15.950000000000003, 16.5)
Subinterval 71: (16.5, 17.050000000000004)
Subinterval 72: (17.050000000000004, 17.6)
Subinterval 73: (17.6, 18.150000000000006)
Subinterval 74: (18.150000000000006, 18.700000000000003)
Subinterval 75: (18.700000000000003, 19.25)
Subinterval 76: (19.25, 19.800000000000004)
Subinterval 77: (19.800000000000004, 20.35)
Subinterval 78: (20.35, 20.900000000000006)
Subinterval 79: (20.900000000000006, 21.450000000000003)
Subinterval 80: (21.450000000000003, 22.0)

Q2. Write a Python program to Generate vector x in the interval [0,15] using numpy package
with 100 subintervals.

In [27]: import numpy as np



x = np.linspace(0, 15,100+1)
print(x)

for i in range(len(x) - 1):
print(f"Subinterval {i + 1}: ({x[i]}, {x[i + 1]})")

[ 0. 0.15 0.3 0.45 0.6 0.75 0.9 1.05 1.2 1.35 1.5 1.65
1.8 1.95 2.1 2.25 2.4 2.55 2.7 2.85 3. 3.15 3.3 3.45
3.6 3.75 3.9 4.05 4.2 4.35 4.5 4.65 4.8 4.95 5.1 5.25
5.4 5.55 5.7 5.85 6. 6.15 6.3 6.45 6.6 6.75 6.9 7.05
7.2 7.35 7.5 7.65 7.8 7.95 8.1 8.25 8.4 8.55 8.7 8.85
9. 9.15 9.3 9.45 9.6 9.75 9.9 10.05 10.2 10.35 10.5 10.65
10.8 10.95 11.1 11.25 11.4 11.55 11.7 11.85 12. 12.15 12.3 12.45
12.6 12.75 12.9 13.05 13.2 13.35 13.5 13.65 13.8 13.95 14.1 14.25
14.4 14.55 14.7 14.85 15. ]
Subinterval 1: (0.0, 0.15)
Subinterval 2: (0.15, 0.3)
Subinterval 3: (0.3, 0.44999999999999996)
Subinterval 4: (0.44999999999999996, 0.6)
Subinterval 5: (0.6, 0.75)
Subinterval 6: (0.75, 0.8999999999999999)
Subinterval 7: (0.8999999999999999, 1.05)
Subinterval 8: (1.05, 1.2)
Subinterval 9: (1.2, 1.3499999999999999)
Subinterval 10: (1.3499999999999999, 1.5)
Subinterval 11: (1 5 1 65)

Q3.Generate vector x in the interval [-7,7] using numpy package with 50 subintervals.
In [29]: import numpy as np

x = np.linspace(-7, 7, 50+1)
print(x)

for i in range(len(x) - 1):
print(f"Subinterval {i + 1}: ({x[i]}, {x[i + 1]})")
[-7.0000000e+00 -6.7200000e+00 -6.4400000e+00 -6.1600000e+00
-5.8800000e+00 -5.6000000e+00 -5.3200000e+00 -5.0400000e+00
-4.7600000e+00 -4.4800000e+00 -4.2000000e+00 -3.9200000e+00
-3.6400000e+00 -3.3600000e+00 -3.0800000e+00 -2.8000000e+00
-2.5200000e+00 -2.2400000e+00 -1.9600000e+00 -1.6800000e+00
-1.4000000e+00 -1.1200000e+00 -8.4000000e-01 -5.6000000e-01
-2.8000000e-01 8.8817842e-16 2.8000000e-01 5.6000000e-01
8.4000000e-01 1.1200000e+00 1.4000000e+00 1.6800000e+00
1.9600000e+00 2.2400000e+00 2.5200000e+00 2.8000000e+00
3.0800000e+00 3.3600000e+00 3.6400000e+00 3.9200000e+00
4.2000000e+00 4.4800000e+00 4.7600000e+00 5.0400000e+00
5.3200000e+00 5.6000000e+00 5.8800000e+00 6.1600000e+00
6.4400000e+00 6.7200000e+00 7.0000000e+00]
Subinterval 1: (-7.0, -6.72)
Subinterval 2: (-6.72, -6.4399999999999995)
Subinterval 3: (-6.4399999999999995, -6.16)
Subinterval 4: (-6.16, -5.88)
Subinterval 5: (-5.88, -5.6)
Subinterval 6: (-5.6, -5.32)
Subinterval 7: (-5.32, -5.04)
Subinterval 8: (-5.04, -4.76)
Subinterval 9: (-4.76, -4.4799999999999995)
Subinterval 10: (-4.4799999999999995, -4.199999999999999)
Subinterval 11: (-4.199999999999999, -3.92)
Subinterval 12: (-3.92, -3.6399999999999997)
Subinterval 13: (-3.6399999999999997, -3.3599999999999994)
Subinterval 14: (-3.3599999999999994, -3.0799999999999996)
Subinterval 15: (-3.0799999999999996, -2.8)
Subinterval 16: (-2.8, -2.5199999999999996)
Subinterval 17: (-2.5199999999999996, -2.2399999999999993)
Subinterval 18: (-2.2399999999999993, -1.959999999999999)
Subinterval 19: (-1.959999999999999, -1.6799999999999997)
Subinterval 20: (-1.6799999999999997, -1.3999999999999995)
Subinterval 21: (-1.3999999999999995, -1.1199999999999992)
Subinterval 22: (-1.1199999999999992, -0.8399999999999999)
Subinterval 23: (-0.8399999999999999, -0.5599999999999996)
Subinterval 24: (-0.5599999999999996, -0.27999999999999936)
Subinterval 25: (-0.27999999999999936, 8.881784197001252e-16)
Subinterval 26: (8.881784197001252e-16, 0.28000000000000114)
Subinterval 27: (0.28000000000000114, 0.5600000000000005)
Subinterval 28: (0.5600000000000005, 0.8400000000000007)
Subinterval 29: (0.8400000000000007, 1.120000000000001)
Subinterval 30: (1.120000000000001, 1.4000000000000004)
Subinterval 31: (1.4000000000000004, 1.6800000000000015)
Subinterval 32: (1.6800000000000015, 1.9600000000000009)
Subinterval 33: (1.9600000000000009, 2.24)
Subinterval 34: (2.24, 2.5200000000000014)
Subinterval 35: (2.5200000000000014, 2.8000000000000007)
Subinterval 36: (2.8000000000000007, 3.080000000000002)
Subinterval 37: (3.080000000000002, 3.360000000000001)
Subinterval 38: (3.360000000000001, 3.6400000000000006)
Subinterval 39: (3.6400000000000006, 3.9200000000000017)
Subinterval 40: (3.9200000000000017, 4.200000000000001)
Subinterval 41: (4.200000000000001, 4.48)
Subinterval 42: (4.48, 4.760000000000002)
Subinterval 43: (4.760000000000002, 5.040000000000001)
Subinterval 44: (5.040000000000001, 5.32)
Subinterval 45: (5.32, 5.600000000000001)
Subinterval 46: (5.600000000000001, 5.880000000000001)
Subinterval 47: (5.880000000000001, 6.160000000000002)
Subinterval 48: (6.160000000000002, 6.440000000000001)
Subinterval 49: (6.440000000000001, 6.720000000000001)
Subinterval 50: (6.720000000000001, 7.0)
Q4. Write a python program to Plot 2D X-axis and Y-axis black color and in the same diagram
plot green triangle with vertices [5,4],[7,4],[6,6].
In [4]: import matplotlib.pyplot as plt
import numpy as np

# Function to plot a triangle
def plot_triangle(vertices, color, label):
triangle = plt.Polygon(vertices, closed=True, edgecolor=color, facecolor='none',a
plt.gca().add_patch(triangle)
for vertex in vertices:
plt.text(vertex[0], vertex[1], f'({vertex[0]}, {vertex[1]})', fontsize=12, ha

# Plotting
plt.axhline(0, color='black', linewidth=1) # X-axis
plt.axvline(0, color='black', linewidth=1) # Y-axis

# Vertices of the green triangle
triangle_vertices = np.array([[5, 4], [7, 4], [6, 6]])

# Plot the green triangle
plot_triangle(triangle_vertices, color='green', label='Green Triangle')

# Add legend and labels
plt.legend()
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('2D Plot with X-axis, Y-axis, and Green Triangle')

# Add grid
plt.grid(True, linestyle='--', alpha=1)

# Set plot limits
plt.xlim(4, 8)
plt.ylim(3, 7)

# Display the plot
plt.show()
Q6. Write a Python Program to reflect the following points about X=0 Plane (or YZ-Plane):

(i) (1,2,3)

(ii) (4,-3,7)

(iii) (-33,-10,2)

In [15]: import numpy as np



def reflect_about_yz_plane(points):
# Define reflection matrix for YZ-plane
reflection_matrix = np.array([
[-1, 0, 0],
[0, 1, 0],
[0, 0, 1]
])

# Convert points to numpy array for matrix multiplication


points_array = np.array(points)

# Reflect the points using matrix multiplication


reflected_points_array = np.dot(points_array, reflection_matrix)

# Convert the reflected points array back to list of tuples


reflected_points = [tuple(reflected_point) for reflected_point in reflected_point

return reflected_points

# Points to be reflected
points = [(1, 2, 3), (4, -3, 7), (-33, -10, 2)]

# Reflect the points about YZ-plane
reflected_points = reflect_about_yz_plane(points)

# Print the original and reflected points
print("Original Points:")
for point in points:
print(point)

print("\nReflected Points about YZ-plane:")
for reflected_point in reflected_points:
print(reflected_point)

Original Points:
(1, 2, 3)
(4, -3, 7)
(-33, -10, 2)

Reflected Points about YZ-plane:


(-1, 2, 3)
(-4, -3, 7)
(33, -10, 2)
Detailed working

In [6]: # Points to be reflected


points = [(1, 2, 3), (4, -3, 7), (-33, -10, 2)]
points

Out[6]: [(1, 2, 3), (4, -3, 7), (-33, -10, 2)]

In [5]: points_array = np.array(points)


points_array

Out[5]: array([[ 1, 2, 3],


[ 4, -3, 7],
[-33, -10, 2]])

In [10]: # Define reflection matrix for YZ-plane


reflection_matrix = np.array([
[-1, 0, 0],
[0, 1, 0],
[0, 0, 1]
])
# Reflect the points using matrix multiplication
reflected_points_array = np.dot(points_array, reflection_matrix)
reflected_points_array

Out[10]: array([[ -1, 2, 3],


[ -4, -3, 7],
[ 33, -10, 2]])

In [14]: for reflected_point in reflected_points:


print(reflected_point)

(-1, 2, 3)
(-4, -3, 7)
(33, -10, 2)

Q7. Write a Python Program to reflect the following points about Y=0 Plane (or XZ-Plane):

(i) (1,2,3)

(ii) (4,-3,7)

(iii) (-33,-10,2)
In [11]: import numpy as np

def reflect_about_xz_plane(points):
# Define reflection matrix for XZ-plane
reflection_matrix = np.array([
[1, 0, 0],
[0, -1, 0],
[0, 0, 1]
])

# Convert points to numpy array for matrix multiplication


points_array = np.array(points)

# Reflect the points using matrix multiplication


reflected_points_array = np.dot(points_array, reflection_matrix)

# Convert the reflected points array back to list of tuples


reflected_points = [tuple(reflected_point) for reflected_point in reflected_point

return reflected_points

# Points to be reflected
points = [(1, 2, 3), (4, -3, 7), (-33, -10, 2)]

# Reflect the points about YZ-plane
reflected_points = reflect_about_xz_plane(points)

# Print the original and reflected points
print("Original Points:")
for point in points:
print(point)

print("\nReflected Points about XZ-plane:")
for reflected_point in reflected_points:
print(reflected_point)

Original Points:
(1, 2, 3)
(4, -3, 7)
(-33, -10, 2)

Reflected Points about XZ-plane:


(1, -2, 3)
(4, 3, 7)
(-33, 10, 2)

Q8. Write a Python Program to reflect the following points about Z=0 Plane (or XY-Plane):

(i) (1,2,3)

(ii) (4,-3,7)

(iii) (-33,-10,2)
In [13]: import numpy as np

def reflect_about_xy_plane(points):
# Define reflection matrix for XY-plane
reflection_matrix = np.array([
[1, 0, 0],
[0, 1, 0],
[0, 0, -1]
])

# Convert points to numpy array for matrix multiplication


points_array = np.array(points)

# Reflect the points using matrix multiplication


reflected_points_array = np.dot(points_array, reflection_matrix)

# Convert the reflected points array back to list of tuples


reflected_points = [tuple(reflected_point) for reflected_point in reflected_point

return reflected_points

# Points to be reflected
points = [(1, 2, 3), (4, -3, 7), (-33, -10, 2)]

# Reflect the points about XY-plane
reflected_points = reflect_about_xy_plane(points)

# Print the original and reflected points
print("Original Points:")
for point in points:
print(point)

print("\nReflected Points about XY-plane:")
for reflected_point in reflected_points:
print(reflected_point)

Original Points:
(1, 2, 3)
(4, -3, 7)
(-33, -10, 2)

Reflected Points about XY-plane:


(1, 2, -3)
(4, -3, -7)
(-33, -10, -2)
S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 8(Study of
Graphical aspects of Three-dimensional
transformation matrix using matplotlib-II)
In [1]: pip install sympy

Requirement already satisfied: sympy in c:\users\krush\anaconda3\lib\site-packages


(1.11.1)
Requirement already satisfied: mpmath>=0.19 in c:\users\krush\anaconda3\lib\site-pa
ckages (from sympy) (1.2.1)
Note: you may need to restart the kernel to use updated packages.

Q1. Write a Python Program to rotate the following points about X-axis by an angle of 45°:

(i) (1,2,3)

(ii) (4,-3,7)

(iii) (-33,-10,2)
In [3]: import numpy as np
import math

def rotate_about_y_axis(points, angle_degrees):
# Convert angle from degrees to radians
angle_radians = math.radians(angle_degrees)

# Define rotation matrix for X-axis


rotation_matrix = np.array([
[1, 0, 0],
[0, math.cos(angle_radians), math.sin(angle_radians)],
[0, -math.sin(angle_radians), math.cos(angle_radians)]
])

# Convert points to numpy array for matrix multiplication


points_array = np.array(points)

# Rotate the points using matrix multiplication


rotated_points_array = np.dot(points_array, rotation_matrix)

# Convert the rotated points array back to list of tuples


rotated_points = [tuple(rotated_point) for rotated_point in rotated_points_array

return rotated_points

# Points to be rotated
points = [(1, 2, 3), (4, -3, 7), (-33, -10, 2)]

# Angle of rotation (in degrees)
angle_degrees = 45

# Rotate the points about X-axis
rotated_points = rotate_about_y_axis(points, angle_degrees)

# Print the original and rotated points
print("Original Points:")
for point in points:
print(point)

print("\nRotated Points about X-axis (45 degrees):")
for rotated_point in rotated_points:
print(rotated_point)

Original Points:
(1, 2, 3)
(4, -3, 7)
(-33, -10, 2)

Rotated Points about X-axis (45 degrees):


(1.0, -0.7071067811865476, 3.5355339059327378)
(4.0, -7.0710678118654755, 2.8284271247461903)
(-33.0, -8.485281374238571, -5.656854249492381)

Detailed working

In [4]: points = [(1, 2, 3), (4, -3, 7), (-33, -10, 2)]
points

Out[4]: [(1, 2, 3), (4, -3, 7), (-33, -10, 2)]


In [5]: points_array = np.array(points)
points_array

Out[5]: array([[ 1, 2, 3],


[ 4, -3, 7],
[-33, -10, 2]])

In [28]: angle_radians = math.radians(angle_degrees)


angle_degrees = 45
rotation_matrix = np.array([
[1, 0, 0],
[0, math.cos(angle_radians), math.sin(angle_radians)],
[0, -math.sin(angle_radians), math.cos(angle_radians)]
])
rotation_matrix

Out[28]: array([[ 1. , 0. , 0. ],
[ 0. , 0.70710678, 0.70710678],
[ 0. , -0.70710678, 0.70710678]])

In [29]: rotated_points_array = np.dot(points_array, rotation_matrix)


rotated_points_array

Out[29]: array([[ 1. , -0.70710678, 3.53553391],


[ 4. , -7.07106781, 2.82842712],
[-33. , -8.48528137, -5.65685425]])

In [6]: print("\nRotated Points about X-axis (45 degrees):")


for rotated_point in rotated_points:
print(rotated_point)

Rotated Points about X-axis (45 degrees):


(1.0, -0.7071067811865476, 3.5355339059327378)
(4.0, -7.0710678118654755, 2.8284271247461903)
(-33.0, -8.485281374238571, -5.656854249492381)

Q2. Write a Python Program to rotate the following points about Y-axis by an angle of 45°:

(i) (1,2,3)

(ii) (4,-3,7)

(iii) (-33,-10,2)
In [30]: import numpy as np
import math

def rotate_about_y_axis(points, angle_degrees):
# Convert angle from degrees to radians
angle_radians = math.radians(angle_degrees)

# Define rotation matrix for Y-axis


rotation_matrix = np.array([
[math.cos(angle_radians), 0, -math.sin(angle_radians)],
[0, 1, 0],
[math.sin(angle_radians), 0, math.cos(angle_radians)]
])

# Convert points to numpy array for matrix multiplication


points_array = np.array(points)

# Rotate the points using matrix multiplication


rotated_points_array = np.dot(points_array, rotation_matrix)

# Convert the rotated points array back to list of tuples


rotated_points = [tuple(rotated_point) for rotated_point in rotated_points_array

return rotated_points

# Points to be rotated
points = [(1, 2, 3), (4, -3, 7), (-33, -10, 2)]

# Angle of rotation (in degrees)
angle_degrees = 45

# Rotate the points about Y-axis
rotated_points = rotate_about_y_axis(points, angle_degrees)

# Print the original and rotated points
print("Original Points:")
for point in points:
print(point)

print("\nRotated Points about Y-axis (45 degrees):")
for rotated_point in rotated_points:
print(rotated_point)

Original Points:
(1, 2, 3)
(4, -3, 7)
(-33, -10, 2)

Rotated Points about Y-axis (45 degrees):


(2.8284271247461903, 2.0, 1.4142135623730951)
(7.778174593052023, -3.0, 2.121320343559643)
(-21.920310216782973, -10.0, 24.748737341529164)

Q3. Write a Python Program to rotate the following points about Z-axis by an angle of 45°:

(i) (1,2,3)

(ii) (4,-3,7)

(iii) (-33,-10,2)
In [31]: import numpy as np
import math

def rotate_about_z_axis(points, angle_degrees):
# Convert angle from degrees to radians
angle_radians = math.radians(angle_degrees)

# Define rotation matrix for Z-axis


rotation_matrix = np.array([
[math.cos(angle_radians), math.sin(angle_radians), 0],
[-math.sin(angle_radians), math.cos(angle_radians), 0],
[0, 0, 1]
])

# Convert points to numpy array for matrix multiplication


points_array = np.array(points)

# Rotate the points using matrix multiplication


rotated_points_array = np.dot(points_array, rotation_matrix)

# Convert the rotated points array back to list of tuples


rotated_points = [tuple(rotated_point) for rotated_point in rotated_points_array

return rotated_points

# Points to be rotated
points = [(1, 2, 3), (4, -3, 7), (-33, -10, 2)]

# Angle of rotation (in degrees)
angle_degrees = 45

# Rotate the points about Z-axis
rotated_points = rotate_about_z_axis(points, angle_degrees)

# Print the original and rotated points
print("Original Points:")
for point in points:
print(point)

print("\nRotated Points about Z-axis (45 degrees):")
for rotated_point in rotated_points:
print(rotated_point)

Original Points:
(1, 2, 3)
(4, -3, 7)
(-33, -10, 2)

Rotated Points about Z-axis (45 degrees):


(-0.7071067811865476, 2.121320343559643, 3.0)
(4.949747468305833, 0.7071067811865476, 7.0)
(-16.263455967290593, -30.405591591021544, 2.0)

Q4. Write a Python program in 3D to rotate the point (1,0,0) through XZ Plane in anticlockwise
direction (Rotation through Y axis) by an angle of 90°.

In [ ]: """Refer Q2. and try it yourself"""

Q5. Write a Python program in 3D to rotate the point (1,0,0) through X Plane in anticlockwise
direction (Rotation through Z axis) by an angle of 90°.
In [ ]: """Refer Q3. and try it yourself"""
S.Y.B.Sc. Comp. Sc. Sem-IV Practical no. 9(Study of
effect of concatenation of Two dimensional and
Three dimensional transformations)
In [2]:  pip install sympy

Requirement already satisfied: sympy in c:\users\krush\anaconda3\lib\site-packa


ges (1.11.1)
Requirement already satisfied: mpmath>=0.19 in c:\users\krush\anaconda3\lib\sit
e-packages (from sympy) (1.2.1)
Note: you may need to restart the kernel to use updated packages.

Sample Problem:

Write a python program to find the combined transformation of the line segment between the points
A[3,2] and B[2,-3] for the following sequence of transformation:

a. Rotation about origin through an angle π/6.

b. Scaling in Y co-ordinate by -4 units.

c. Uniform scaling by -6.4 units.

d. Shearing in Y direction by 5 units.


In [7]:  # Method 1
from sympy import *
from math import *

# Define points A and B
A = (3, 2)
B = (2, -3)

# Create a segment object S using points A and B
S = Segment(A, B)
print("End points of line Seg AB is:", S,"\n")

# Rotate the segment S by an angle of 30 degrees (pi/6 radians)
S = S.rotate(pi/6)
print("Line seg AB after rotation through an angle 30 is:\n", S,"\n")

# Scale the segment S in the Y-coordinate by a factor of -4
S = S.scale(1, -4)
print("Line seg AB after Scaling in Y co-ordinate by factor -4 is:\n", S,"\n")

# Uniformly scale the segment S by a factor of -6.4
S = S.scale(-6.4, -6.4)
print("Line seg AB after Uniform Scaling by factor -6.4 is:\n", S,"\n")

# Extract the points of the transformed segment
points = S.points
p = points[0]
q = points[1]

T=Matrix([[1, 5, 0], [0, 1, 0], [0, 0, 1]])
print(T,"\n")

# Apply a 2D transformation to the points using a Shearing ion Y direction by 5 u
p1 = p.transform(T)
q1 = q.transform(T)

# Create a new segment P using the transformed points
P = Segment(p1, q1)
print("Transformed object is:\n", P)

End points of line Seg AB is: Segment2D(Point2D(3, 2), Point2D(2, -3))

Line seg AB after rotation through an angle 30 is:


Segment2D(Point2D(39951905283833/25000000000000, 40400635094611/1250000000000
0), Point2D(40400635094611/12500000000000, -39951905283833/25000000000000))

Line seg AB after Scaling in Y co-ordinate by factor -4 is:


Segment2D(Point2D(39951905283833/25000000000000, -40400635094611/312500000000
0), Point2D(40400635094611/12500000000000, 39951905283833/6250000000000))

Line seg AB after Uniform Scaling by factor -6.4 is:


Segment2D(Point2D(-25569219381653/2500000000000, 827405006737633/1000000000000
0), Point2D(-25856406460551/1250000000000, -8182150202129/200000000000))

Matrix([[1, 5, 0], [0, 1, 0], [0, 0, 1]])

Transformed object is:


Segment2D(Point2D(-25569219381653/2500000000000, 316020619104573/1000000000000
0), Point2D(-25856406460551/1250000000000, -144336376852849/1000000000000))
In [17]:  T

 1 5 0
Out[17]:
 0 1 0 
 0 0 1
In [ ]:  ​

Q1. Find the combined transformation of the line segment between the points A[5,-2] & B[4,3]by
using Python program for the following sequence of transformations:

(i) Rotation about origin through an angle π.

(ii) Scaling in X-coordinate by 2 units.

(iii) Reflection through the line y = -x.

(iv) Shearing in X direction by 4 units.


In [10]:  from sympy import *
from math import *

# Define points A and B
A = (5, -2)
B = (4, 3)

# Create a segment object S using points A and B
S = Segment(A, B)
print("End points of line Seg AB is:", S,"\n")

# Rotate the segment S by an angle of 30 degrees (pi/6 radians)
S = S.rotate(pi)
print("Line seg AB after rotation through an angle 30 is:\n", S,"\n")

# Scale the segment S in the X-coordinate by a factor of 2
S = S.scale(2, 1)
print("Line seg AB after Scaling in X co-ordinate by factor 2 is:\n", S,"\n")

# Reflection through y=-x
x,y=symbols('x y')
S=S.reflect(Line(x+y+0))

print("Line seg AB after Reflection through y=-x is:\n", S,"\n")

# Extract the points of the transformed segment
points = S.points
p = points[0]
q = points[1]

T=Matrix([[1, 0, 0], [4, 1, 0], [0, 0, 1]])
print(T,"\n")

# Apply a 2D transformation to the points using a Shearing ion X direction by 4 u
p1 = p.transform(T)
q1 = q.transform(T)

# Create a new segment P using the transformed points
P = Segment(p1, q1)
print("Transformed object is:\n", P)

End points of line Seg AB is: Segment2D(Point2D(5, -2), Point2D(4, 3))

Line seg AB after rotation through an angle 30 is:


Segment2D(Point2D(-5, 2), Point2D(-4, -3))

Line seg AB after Scaling in Y co-ordinate by factor -4 is:


Segment2D(Point2D(-10, 2), Point2D(-8, -3))

Line seg AB after Reflection through y=-x is:


Segment2D(Point2D(-2, 10), Point2D(3, 8))

Matrix([[1, 0, 0], [4, 1, 0], [0, 0, 1]])

Transformed object is:


Segment2D(Point2D(38, 10), Point2D(35, 8))

In [11]:  T

 1 0 0
Out[11]:
 4 1 0 
 0 0 1
Q2. Find the combined transformation of the line segment between the points A[4,-1] & B[3,0] by
using Python program for the following sequence of transformations: -

(i) Rotation about origin through an angle π.

(ii) Shearing in Y direction by 4.5 units.

(iii) Scaling in X− coordinate by 3 units.

(iv) Reflection through the line y = x.

In [ ]:  """Refer Q1. and try it yourself"""

Q3. Find the combined transformation of the line segment between the points A[7,-2] & B[6,2]by
using Python program for the following sequence of transformations:

(i) Rotation about origin through an angle π/3 .

(ii) Scaling in X− coordinate by 7 units.

(iii) Uniform scaling by −4 units.

(iv) Reflection through the line X-axis.

In [ ]:  """Refer Q1. and try it yourself"""

Q4. Find the combined transformation of the line segment between the points A[4,-1] & B[3,2] by
using Python program for the following sequence of transformations:

(i) Rotation about origin through an angle π/4 .

(ii) Shearing in Y direction by 4 units.

(iii) Scaling in X− coordinate by 5 units.

(iv) Reflection through Y-axis.

In [ ]:  """Refer Q1. and try it yourself"""

Q5. Write a python program to find the combined transformation of the line segment between
the points A[5,3] & B[1,4] for the following sequence of transformations:

(i) Rotate about origin through an angle π/2 (ii) Uniform scaling by −3.5 units. (iii) Scaling in Y− axis by
5 units. (iv) Shearing in X and Y direction by 3 and 4 units respectively.

In [ ]:  """Refer Q1. and try it yourself"""

Q6. Write a Python program to find the combined transformation of the line segment between
the points A[5,3] and B[1,4] for the following sequence of transformations:

(i) First rotation about origin through an angle π/2.

(ii) Followed by scaling in x co-ordinate by 5 units.

(iii) Followed by reflection through the line y=-x


In [ ]:  """Refer Q1. and try it yourself"""

Q7. Find combined transformation of the line segment between the points A[4,-1] and B[3,0] for
the following sequence of transformations:

First rotation about origin through an angle π^c;

followed by scaling in x coordinate by 3 units;

followed by reflection through the line y = x.

In [ ]:  """Refer Q1. and try it yourself"""


S.Y.B.Sc. Comp. Sc. Sem-IV Practical no.
10(Generation of Bezier curve using given control
points)
In [1]:  pip install bezier

Requirement already satisfied: bezier in c:\users\krush\anaconda3\lib\site-pack


ages (2023.7.28)
Requirement already satisfied: numpy>=1.24.2 in c:\users\krush\anaconda3\lib\si
te-packages (from bezier) (1.24.3)
Note: you may need to restart the kernel to use updated packages.

In [2]:  pip install matplotlib

Requirement already satisfied: matplotlib in c:\users\krush\anaconda3\lib\site-


packages (3.7.1)
Requirement already satisfied: contourpy>=1.0.1 in c:\users\krush\anaconda3\lib
\site-packages (from matplotlib) (1.0.5)
Requirement already satisfied: cycler>=0.10 in c:\users\krush\anaconda3\lib\sit
e-packages (from matplotlib) (0.11.0)
Requirement already satisfied: fonttools>=4.22.0 in c:\users\krush\anaconda3\li
b\site-packages (from matplotlib) (4.25.0)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\users\krush\anaconda3\li
b\site-packages (from matplotlib) (1.4.4)
Requirement already satisfied: numpy>=1.20 in c:\users\krush\anaconda3\lib\site
-packages (from matplotlib) (1.24.3)
Requirement already satisfied: packaging>=20.0 in c:\users\krush\anaconda3\lib
\site-packages (from matplotlib) (23.0)
Requirement already satisfied: pillow>=6.2.0 in c:\users\krush\anaconda3\lib\si
te-packages (from matplotlib) (9.4.0)
Requirement already satisfied: pyparsing>=2.3.1 in c:\users\krush\anaconda3\lib
\site-packages (from matplotlib) (3.0.9)
Requirement already satisfied: python-dateutil>=2.7 in c:\users\krush\anaconda3
\lib\site-packages (from matplotlib) (2.8.2)
Requirement already satisfied: six>=1.5 in c:\users\krush\anaconda3\lib\site-pa
ckages (from python-dateutil>=2.7->matplotlib) (1.16.0)
Note: you may need to restart the kernel to use updated packages.

In [6]:  import numpy as np

In [7]:  from sympy import*

Q1. Using python, generate triangle with vertices (0,0),(4,0),(4,3) check whether the triangle is
Right angle triangle.
In [5]:  # Method 1
import math

# Define the vertices of the triangle
vertex1 = (0, 0)
vertex2 = (4, 0)
vertex3 = (4, 3)

# Calculate the lengths of the sides
side1 = math.sqrt((vertex2[0] - vertex1[0])**2 + (vertex2[1] - vertex1[1])**2)
side2 = math.sqrt((vertex3[0] - vertex2[0])**2 + (vertex3[1] - vertex2[1])**2)
side3 = math.sqrt((vertex1[0] - vertex3[0])**2 + (vertex1[1] - vertex3[1])**2)

# Sort the sides in ascending order
sides = sorted([side1, side2, side3])

# Check if it's a right-angled triangle using the Pythagorean theorem
is_right_triangle = math.isclose(sides[0]**2 + sides[1]**2, sides[2]**2)

# Print the result
print("Is the triangle a right-angled triangle?", is_right_triangle)

Is the triangle a right-angled triangle? True

In [29]:  # Method 2
from sympy import*
T1=Triangle(Point(0,0),Point(4,0),Point(4,3))
T1.is_right()

Out[29]: True

Q2. Using python, generate triangle with vertices (0,0),(4,0),(2,4), check whether the triangle is
isosceles triangle.

In [ ]:  """Refer Practical no. 5"""

Q3. Generate line segment having endpoints (0,0) and (10,10) find midpoint of line segment.

In [6]:  from sympy import*


S1=Segment(Point(3,2),Point(2,-3))
S1.midpoint

Out[6]:
Point2D( 52 ,− 12 )
In [7]:  from sympy import Point, Segment

# Define a segment with endpoints (3, 2) and (2, -3)
S1 = Segment(Point(3, 2), Point(2, -3))

# Access the midpoint of the segment
midpoint = S1.midpoint

# Print the midpoint
print(midpoint)

Point2D(5/2, -1/2)

Q4. Generate line segment having endpoints (2,3) and (4,3) find midpoint of line segment.

In [ ]:  """Refer Practical no. 3"""

Q5. Draw a Bezier curve of degree 3 and 4 polygonal vertices (1,1), (2,3), (4,3) and (6,4)

In [11]:  # Create a 2x4 array (2D) representing the control points of the Bezier curve
# The first row represents x-coordinates, and the second row represents y-coordin
nodes = np.asfortranarray([[1, 2, 4, 6], [1, 3, 3, 4]])

# Create a Bezier curve object using the control points and set the degree to 3
curve = bezier.Curve(nodes, 3)

# Display the Bezier curve object
curve

# Set the style for plotting using seaborn
seaborn.set()

# Plot the Bezier curve using the 'plot' method with 1000 points for smoothness o
ax = curve.plot(num_pts=1000,color='brown')
Q6. Plot the Bezier curve with 6 control points (1,2), (4,0), (8,3), (5,4), (3,3) and (6,8).

In [9]:  import numpy as np


import bezier
import seaborn

# Create a 2x6 array (2D) representing the control points of the Bezier curve
# The first row represents x-coordinates, and the second row represents y-coordin
nodes = np.asfortranarray([[1, 4, 8, 5, 3, 6], [2, 0, 3, 4, 3, 8]])

# Create a Bezier curve object using the control points and set the degree to 5
curve = bezier.Curve(nodes, 5)

# Display the Bezier curve object
curve

# Set the style for plotting using seaborn
seaborn.set()

# Plot the Bezier curve using the 'plot' method with 1000 points for smoothness
ax = curve.plot(num_pts=1000,color='violet')

np.asfortranarray() is a function call from the NumPy library. It is used to create a NumPy array
with Fortran-style memory layout.

Let's consider a 2x3 matrix:

123

456

In Python (row-major order), this would be stored in memory like this: [1, 2, 3, 4, 5, 6]

In Fortran (column-major order), it would be stored like this:[1, 4, 2, 5, 3, 6]


Q7. Using Python plot the Bezier curve with 4 control points (0, 2), (2, 3), (3, 2), (2, 0).

In [27]:  # Import necessary libraries


import numpy as np
import bezier
import matplotlib.pyplot as plt

# Create a 2x4 array (2D) representing the control points of the Bezier curve
# The first row represents x-coordinates, and the second row represents y-coordin
nodes = np.asfortranarray([[0, 2, 3, 2], [2, 3, 2, 0]])

# Create a Bezier curve object using the control points and set the degree to 3
curve = bezier.Curve(nodes, 3)

# Display the Bezier curve object
curve

# Set the style for plotting (optional)
plt.style.use('seaborn-darkgrid')

# Plot the Bezier curve using the 'plot' method with 1000 points for smoothness
# Specify the color parameter to change the color of the curve (e.g., 'k' for bla
ax = curve.plot(num_pts=1000, color='k')

# Show the plot
plt.show()

C:\Users\krush\AppData\Local\Temp\ipykernel_14384\1566443997.py:17: MatplotlibD
eprecationWarning: The seaborn styles shipped by Matplotlib are deprecated sinc
e 3.6, as they no longer correspond to the styles shipped by seaborn. However,
they will remain available as 'seaborn-v0_8-<style>'. Alternatively, directly u
se the seaborn API instead.
plt.style.use('seaborn-darkgrid')

Feel free to explore these styles to find the one that best fits your preferences and the
requirements of your plots.
'ggplot': Emulates the style of the popular ggplot library in R.

'seaborn-bright': A brighter version of the seaborn style with lighter grid lines.

'seaborn-muted': A muted version of the seaborn style with softer colors.

'seaborn-pastel': A pastel version of the seaborn style with lighter colors.

'seaborn-colorblind': A colorblind-friendly version of the seaborn style.

'seaborn-dark': A darker version of the seaborn style without grid lines.

'seaborn-poster': A style suitable for creating poster-style plots with larger fonts and thicker lines.

'seaborn-whitegrid': A white background with grid lines.

Example showing different styles of seaborn

In [19]:  import matplotlib.pyplot as plt


import numpy as np

# Data for plotting
x = np.linspace(0, 10, 100)
y = np.sin(x)

# List of styles to iterate over
styles = ['default', 'ggplot', 'seaborn-bright', 'seaborn-muted',
'seaborn-pastel', 'seaborn-colorblind', 'seaborn-dark',
'seaborn-poster', 'seaborn-whitegrid']

# Plotting each style
for style in styles:
plt.figure()
plt.style.use(style)
plt.plot(x, y)
plt.title(f'Plot with style: {style}')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True)
plt.show()
In [ ]:  ​

You might also like