APL Manual 20 June 2024.PDF
APL Manual 20 June 2024.PDF
SEMESTER: IV
COURSE CODE: 23EC4AEAPL
Special thanks to the below faculties who have contributed towards bringing this
Manual for students reference.
Dr.Feroz Morab, Assistant Professor
Dr. Karthikeya G.S, Assistant Professor
Dr.Hemavathi D, Assistant Professor
Dr. Shivkumar K, Assistant Professor
Mrs.Pooja A P, Assistant Professor
Mr. Eesha D, Assistant Professor
Yashaswini, Assistant Instructor
Course Syllabus
CourseTi MATHEMATICSCONCEPTSUSINGPYTHON
tle
CourseC 22EC4AEMCP Credits 1 L–T–P 0:0:1
ode
CIE 50Marks(100%weightage) SEE 50Marks(100%weightage)
CourseOutcomes:
Attheendofthecourse,studentswillhavetheabilityto:
CO1 UnderstandPythonlibraries,OOPConceptsinPythonProgramming
CO2 Applydifferentmathematicalconcepts:ProbabilityandStatistics,Laplace,Fo
urierand z-Transformsusing pythonIDE platform (Jupyternotebook,
pycharm, etc.)
CO3 Implementreal-timeapplicationsinsignalanalysisandcontrolsystems
ListofExperiments
• Basics of Python and Python Modules
1. Program to find the best of two test average marks out of three test’s marks
accepted from the user.
2. Program to generate a Fibonacci sequence up to specified length.
3. Develop a program to check whether a given number/character is
Palindrome or not.
4. Develop a program to convert Decimal to binary, Octal and Hexa-decimal
and vice-versa using functions and Loops.
55
• OOPS Concepts in Python Programming: Classes, Objects and
Inheritance
5. Declare a base class to calculate Resistance from voltage and current and
extend the class to calculate inductance and capacitance with varying voltage
and current values with respect to time.
6. By using the concept of inheritance, write a program to find the area of
triangle, circle and rectangle.
• Application to Field Theory
7. Demonstration of electric field lines due to a point charge
8. Standing waves animation
• Application to signals and systems and control systems
9. Develop a Program for Sine Wave Generation.
10. Program to display pole – zero plot for a given transfer function.
11. Program to solve a given 2nd order difference equation using Z transform.
12. Program to solve a given 2nd order differential equation using
Laplace transform.
13. Program to display Bode plot for a given second order system.
14. Program to display Nyquist plot for a given second order system.
ReferenceBooks:
1. Students must and should maintain adedicated observation book for lab,
which will be continuous evaluated on a weekly basis.
2. The programs executed in the lab should be documented and the record
must be submitted.
3. The Activity programs should be practiced by students and a printed report
of the same should be submitted.
Note:Uniqueness in data, variables and programming logic are
expected from each Individual. Else it will be treated as Malpractice.
INSTRUCTIONS
1. Students must and should maintain an observation book which will be evaluated
on a continuous basis.
2. The programs executed in the lab should be documented and the record should be
submitted.
3. The Activity programs should be practiced by students and a printed report of the
same should be submitted.
Note: Uniqueness in data and variables are expected from each student.
print("Average of best two test marks out of three test’s marks is", avgMarks);
Output:
Enter marks for test1 : 45
Enter marks for test2 : 39
Enter marks for test3 : 48
Average of best two test marks out of three test’s marks is 46.5
def f(n):
if n<=1:
return n
else:
return f(n-1)+f(n-2)
num=int(input("Number of terms : "))
for i in range(num):
print(f(i))
Output:
Number of terms : 9
0
1
1
2
3
5
8
13
21
for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i),"appears", str_val.count(str(i)), "times");
Output:
Enter a value : 1234234
Not Palindrome
Output:
Enter a char: malayalam
Palindrome
Output:Enter a deciamlnumber : 34
Decial Binary Equivalent Number :100010
II OOPSConceptsinPythonProgramming:Classes,Objects
andInheritance.
5. Declare a base class to calculate Resistance from voltage and current and
extend the class to calculate inductance and capacitance with varying
voltage and current values with respect to time.
class ResistanceCalculator:
def __init__(self, voltage, current):
self.voltage = voltage
self.current = current
defcalculate_resistance(self):
if self.current != 0:
return self.voltage / self.current
else:
return float('inf')
class InductanceCalculator(ResistanceCalculator):
def __init__(self, voltage, current):
super().__init__(voltage, current)
defcalculate_inductance(self, frequency):
if self.current != 0 and frequency != 0:
return self.voltage / (2 * 3.14159 * frequency * self.current)
else:
return float('inf')
class CapacitanceCalculator(ResistanceCalculator):
def __init__(self, voltage, current):
super().__init__(voltage, current)
defcalculate_capacitance(self, frequency):
if self.current != 0 and frequency != 0:
return self.current / (2 * 3.14159 * frequency * self.voltage)
else:
return float('inf')
# Usage example:
voltage_value = 220 # Volts
current_value = 0.1 # Amperes
frequency_value = 50 # Hertz
# Calculate resistance
resistance_calculator = ResistanceCalculator(voltage_value, current_value)
resistance_result = resistance_calculator.calculate_resistance()
print("Resistance:", resistance_result, "ohms")
# Calculate inductance
inductance_calculator = InductanceCalculator(voltage_value, current_value)
inductance_result = inductance_calculator.calculate_inductance(frequency_value)
print("Inductance:", inductance_result, "Henries")
# Calculate capacitance
capacitance_calculator = CapacitanceCalculator(voltage_value, current_value)
capacitance_result =
Capacitance_calculator.calculate_capacitance(frequency_value)
print("Capacitance:", capacitance_result, "Farads")
Output:
Resistance = 2200.0 ohms
Inductance = 0.0022 henries
Capacitance = 0.000144 farads
import math
class Shape:
def __init__(self):
self.area = 0
self.name = ""
defshowArea(self):
print("The area of the", self.name, "is", self.area, "units")
class Circle(Shape):
def __init__(self,radius):
self.area = 0
self.name = "Circle"
self.radius = radius
defcalcArea(self):
self.area = math.pi * self.radius * self.radius
class Rectangle(Shape):
def __init__(self,length,breadth):
self.area = 0
self.name = "Rectangle"
self.length = length
self.breadth = breadth
defcalcArea(self):
self.area = self.length * self.breadth
class Triangle(Shape):
def __init__(self,base,height):
self.area = 0
self.name = "Triangle"
self.base = base
self.height = height
defcalcArea(self):
self.area = self.base * self.height / 2
c1 = Circle(5)
c1.calcArea()
c1.showArea()
r1 = Rectangle(5, 4)
r1.calcArea()
r1.showArea()
t1 = Triangle(3, 4)
t1.calcArea()
t1.showArea()
Output:
The area of the Circle is 78.53981633974483 units
The area of the Rectangle is 20 units
The area of the Triangle is 6.0 units
import numpy as np
import matplotlib.pyplot as plt
# Constants
k = 8.99e9 # Coulomb's constant, N m²/C²
q = 1e-9 # Charge, C
# Plotting
fig, ax = plt.subplots(figsize=(8, 8))
color = np.log(np.hypot(Ex, Ey))
# Set limits
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)
plt.show()
Output:
8. Develop a program on Standing waves animation
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Parameters
L = 10 # Length of the string
k = 2 * np.pi / L # Wave number
omega = 2 * np.pi # Angular frequency
A = 1 # Amplitude
x = np.linspace(0, L, 1000) # Position along the string
Output:
IV Application to signals and systems and controls systems.
# Example usage
frequency = 5 # Frequency of the sine wave in Hz
amplitude = 1.0 # Amplitude of the sine wave
duration = 2 # Duration of the sine wave in seconds
sampling_rate = 44100 # Sampling rate (number of samples per second)
time_values,
sine_wave = generate_sine_wave(frequency, amplitude, duration, sampling_rate)
# Plot the sine wave
plt.figure(figsize=(8, 4))
plt.plot(time_values, sine_wave)
plt.xlabel('Time (seconds)')
plt.ylabel('Amplitude')
plt.title('Sine Wave')
plt.grid(True)
plt.show()
Output:
Output:
11.Program to solve a given 2nd order difference equationusing Z transform.
import numpy as np
import matplotlib.pyplot as plt
defunilateral_z_transform_difference_equation(a, x):
n = len(x)
y = np.zeros(n)
y[0] = x[0] # Initial condition
for i in range(1, n):
y[i] = a * y[i-1] + x[i]
return y
# Define the difference equation parameters
a = 0.5
# Generate an input sequence
n_samples = 10
x = np.ones(n_samples)
# Impulse sequence
# Solve the difference equation using the unilateral Z-transform
y = unilateral_z_transform_difference_equation(a, x)
# Print the output sequence
print("Output sequence (y):", y)
# Plot the input and output sequences
plt.stem(range(n_samples), x, basefmt="b-", linefmt="b-", markerfmt="bo", label="Input
x[n]")
plt.stem(range(n_samples), y, basefmt="r-", linefmt="r-", markerfmt="ro", label="Output
y[n]")
plt.xlabel("n")
plt.ylabel("Amplitude")
plt.title("Difference Equation Solution using Unilateral Z-Transform")
plt.legend()
plt.show()
Output:
12. Program to solve a given 2ndorder differential equation using Laplace
transform.
import sympy as sp
from scipy import signal
t,s=sp.symbols('t,s')
#y"+5y’+6y=0
#y(0)=0,y'(0)=2
#s^2L[y(s)]-y'(0)-y(0)+5sL[y(t)]-y(0)+6L[y(t)]
#s^2L[y(s)]-5sL[y(t)]+6L[y(t)]=y(0)+y’(0)
coeff=[1,5,6]
initial_cond=[0,2] #y(0),y'(0)
l_eq_lhs=(coeff[0]*(s**2)+coeff[1]*(s)+coeff[2])
eq_rhs=initial_cond[0]+initial_cond[1]
l_eq_rhs=eq_rhs/s
tf=l_eq_rhs/l_eq_lhs
l_eq=sp.inverse_laplace_transform(tf,s,t)
print(l_eq)
Output:
(exp(3*t) - 3*exp(t) + 2)*exp(-3*t)*Heaviside(t)/3
Note:
The Heaviside step function, often denoted as H(t), is defined as:
H(t) = 0 for t < 0 h(t) for t>=0
import numpy as np
import matplotlib.pyplot as plt
from import signal
# Define the transfer function
numerator = [1]
denominator = [1, 2, 1] # Example: Second-order system (s^2 + 2s + 1)
system = signal.TransferFunction(numerator, denominator)
# Frequency range for Bode plot
omega = np.logspace(-2, 2, 1000)
# Calculate frequency response
_, mag, phase = signal.bode(system, omega)
# Plot Bode magnitude plot
plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.semilogx(omega, mag)
plt.xlabel('Frequency (rad/s)')
plt.ylabel('Magnitude (dB)')
plt.title('Bode Magnitude Plot')
# Plot Bode phase plot
plt.subplot(2, 1, 2)
plt.semilogx(omega, phase)
plt.xlabel('Frequency (rad/s)')
plt.ylabel('Phase (degrees)')
plt.title('Bode Phase Plot')
plt.tight_layout()
plt.show()
OUTPUT:
14.Program to display Nyquist plot for a given second order system.
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
plt.xlabel('Real Part')
plt.ylabel('Imaginary Part')
plt.title('Nyquist Plot')
plt.grid(True)
plt.axis('equal') # Equal aspect ratio
plt.show()
Output:
ACTIVITY PROGRAMS
Output:
Enter octal Number : 345
Hexadecimal Number = E5
2. Write a python program to implement insertion sort and merge sort using
lists.
#Insertion sort
definsertion_sort(lst):
for i in range(1, len(lst)):
key = lst[i]
j=i-1
while j >= 0 and key <lst[j]:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = key
lst=eval(input("Enter the list to be sorted : "))
insertion_sort(lst)
print("Sorted list :",lst)
Output:
Enter the list to be sorted : [33,22,1,56,78,93]
Sorted list : [1, 22, 33, 56, 78, 93]
#merge sort
defmerge_sort(lst):
if len(lst) > 1:
mid = len(lst) // 2
left_half = lst[:mid]
right_half = lst[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
while i<len(left_half) and j <len(right_half):
if left_half[i] <right_half[j]:
lst[k] = left_half[i]
i += 1
else:
lst[k] = right_half[j]
j += 1
k += 1
while i<len(left_half):
lst[k] = left_half[i]
i += 1
k += 1
while j <len(right_half):
lst[k] = right_half[j]
j += 1
k += 1
lst=eval(input("Enter the list to be sorted : "))
merge_sort(lst)
print(lst)
Output:
Enter the list to be sorted : [66,45,43,89,23,12]
Sorted List : [12, 23, 43, 45, 66, 89]
#random
import random
a=random.randrange(1,100)
print("Random Number : ",a)
Sample Output:
Random Number ; 46
#shuffle
import random
l=["apple", "orange", "banana"]
print("Original List : ",l)
random.shuffle(l)
print("Shuffled List : ",l)
Sample Output:
Original List : ["apple", "orange", "banana"]
Shuffled List : ["banana", "orange", "apple"]
#uniform
import random
print(random.uniform(10,20))
Sample Output:
16.70368719166577
deftoString(List):
return ''.join(List)
defpermute(a, l, r):
if l == r:
print (toString(a))
else:
for i in range(l, r + 1):
a[l], a[i] = a[i], a[l]
permute(a, l + 1, r)
a[l], a[i] = a[i], a[l]
string = '123'
n = len(string)
a = list(string)
permute(a, 0, n-1)
Output:
123
132
213
231
321
312
Output:
Enter a list of integer : [1,2,3,4]
Enter the number of terms : 2
12
13
14
21
23
24
import math
import numpy as np
import matplotlib.pyplot as plt
defgenerate_cos_wave(freq, amplitude, duration, sampling_rate):
num_samples = int(duration * sampling_rate)
time_period = 1.0 / sampling_rate
time_values = np.arange(0, duration, time_period)
cos_wave = amplitude * np.cos(2 * np.pi * freq * time_values)
return time_values, cos_wave
frequency = 5
amplitude = 1.0
duration = 2
sampling_rate = 44100
time_values, cos_wave = generate_cos_wave(frequency, amplitude, duration,
sampling_rate)
plt.figure(figsize=(8, 4))
plt.plot(time_values, cos_wave)
plt.xlabel('Time (seconds)')
plt.ylabel('Amplitude')
plt.title('Cosine Wave')
plt.grid(True)
plt.show()
Output:
7. Program to solve a given 1st order difference equation using Z transform.
import numpy as np
import matplotlib.pyplot as plt
defdifference_equation(a, x):
n = len(x)
y = np.zeros(n)
y[0] = x[0]
for i in range(1, n):
y[i] = a * y[i-1] + x[i]
return y
a = 0.5
n_samples = 10
x = np.ones(n_samples)
y = difference_equation(a, x)
print("Output sequence (y):", y)
plt.stem(range(n_samples), x, basefmt="b-", linefmt="b-", markerfmt="bo", label="Input
x[n]")
plt.stem(range(n_samples), y, basefmt="r-", linefmt="r-", markerfmt="ro", label="Output
y[n]")
plt.xlabel("n")
plt.ylabel("Amplitude")
plt.title("Difference Equation Solution using Unilateral Z-Transform")
plt.legend()
plt.show()
Output:
8. Program to solve a given 1st order differential equation using Laplace
transform
import sympy as sp
t,s,Y=sp.symbols('t s Y')
ode=sp.Eq(sp.diff(Y,t)+3*Y,3*sp.exp(-4*t))
l_eq=sp.laplace_transform(ode.lhs-ode.rhs,t,s,noconds=True)
y_s=sp.solve(l_eq,Y)[0]
solution=sp.inverse_laplace_transform(Y_s,s,t,noconds=True)
print(solution)
Output:
DiracDelta(t) - 4*exp(-4*t)*Heaviside(t)
#mean
n=len(xi)
sum_xifi=0
sum_fi=0
for i in range(n):
sum_xifi+=(xi[i]*fi[i])
sum_fi+=fi[i]
mean=(sum_xifi/sum_fi)
print("Mean = ",mean)
#median
xi1=xi
for i in range(n):
for j in range(fi[i]-1):
xi1.append(xi[i])
xi_asc=sorted(xi1)
n1=len(xi_asc)
if n1%2==0:
median=(xi_asc[int(n1/2)]+xi_asc[int((n1/2)+1)])/2
else :
median=xi_asc[(n1+1)/2]
print("Median = ",median)
#mode
max1=fi[1]
for i in range(1,n):
if fi[i]>max1:
mode=xi[i]
print("Mode = ",mode)
#varience
sum2=0
for i in range(n):
sum2+=(fi[i]*(xi[i]-mean)**2)
var=sum2/n1
print("Varience = ",var)
#Standard Deviation
std=math.sqrt(var)
print("Standard Deviation = ",std)
Output:
Mean = 13.625
Median = 11
Mode = 30.453
Variance = 30.453
Standard Deviation = 5.51494
import random
# prints a random value from the list
list1 = [1, 2, 3, 4, 5, 6]
print(random.choice(list1))
Output:
6
R
import random
random_float = random.random()
print("Random float:", random_float)
Output:
Output:
Random integer: 97
a. Using List
from itertools import permutations
defcalculate_permutations(elements, r):
perms = permutations(elements, r)
return list(perms)
# Example usage
elements = [1, 2, 3]
r=2
permutations = calculate_permutations(elements, r)
from itertools import permutations
defcalculate_permutations(elements, r):
perms = permutations(elements, r)
return list(perms)
# Example usage
elements = [1, 2, 3]
r=2
permutations = calculate_permutations(elements, r)
print(permutations)
Output:
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
Output:
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
11. Program to print all permutations of coin tossing for a given number of
flips.
import random
flips = 0
heads = 0
tails = 0
output:
12. Program to print all combinations of the dice using recursion and
memorization.
Algorithm:
1. If k = 1, create a list with all possible rolls of one die and return it.
2. If k > 1 and the list of all possible rolls of k-1 dice has already been computed, for
each combination of rolls of k-1 dice add all possible rolls of 3.
3. .one die to get all possible rolls of k dice.
4. Store the result in a memoization table to avoid recomputing already computed
values.
5. Return the list of all possible rolls of k dice.
defdice_combinations(k, memo={}):
if k == 1:
memo[1] = [(i,) for i in range(1, 7)]
return memo[1]
elif k in memo:
return memo[k]
else:
prev_res = dice_combinations(k-1, memo)
res = []
k=2
print(dice_combinations(k))
output:
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3,
1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1),
(5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)
13. Program to solve a given 1st order differential equation using Laplace
transform
import sympy as sp
t,s,Y=sp.symbols('t s Y')
ode=sp.Eq(sp.diff(Y,t)+3*Y,3*sp.exp(-4*t))
l_eq=sp.laplace_transform(ode.lhs-ode.rhs,t,s,noconds=True)
y_s=sp.solve(l_eq,Y)[0]
solution=sp.inverse_laplace_transform(Y_s,s,t,noconds=True)
print(solution)
Output:
DiracDelta(t) - 4*exp(-4*t)*Heaviside(t)