SC Lab Record
SC Lab Record
1
LIST OF EXPERIMENTS
Expt. No Date Experiment Name Page Signature
No
1. FAMILIARISATION WITH 1-12
PYTHON
1.1 19-07-24 Assign values to different variables 1
and find their data types.
2. 13-21
INTRODUCTION TO
VECTORISED
COMPUTING AND
2
PLOTTING
2.1 02-08-24 Understanding indexing and basic 13
operations with python list
3. 22-27
SYSTEM OF LINEAR
EQUATIONS AND
EIGENVALUES
3.1 09-08-24 Solving system of linear equations 22
5. NUMERICAL 31-36
DIFFERENTIATION AND
INTEGRATION
5.1 23-08-24 Compute and plot derivatives of sin, 31
cos, sinh, cosh functions
5.2 23-08-24 Numerical integration of 4t2+3 using 34
i) Trapezoidal rule ii) Simpson's rule
3
6.2 06-09-24 Implement and plot the functions f(t) 40
= cos t and f(t) = cos t.cos 5t + cos5t
9. CONVERGENCE OF 58-61
FOURIER SERIES
9.1 04-10-24 4 1 2π 3t 1 58
[1- cos
Plot f(t) = + cos
π 3 T 5
2π 5t 1 2π 7t
- cos +.....]
T 7 T
9.2 04-10-24 Verify the Madhava series for π = 60
1 1 1
4[1 - + - + …..]
3 5 7
4
EXPERIMENT NO. 1
FAMILIARISATION WITH PYTHON
AIM:
i) Familiarise with the data types - int, float, string and list
PROGRAMS:
a) Algorithm
● Start
● Initialise variables a, b, c, d with an integer, float, string and list value
respectively
● Print the variable name along with the data type of the variables using
type(variable) function
● Stop
b) Code
a=3
b=10.23
c='sample'
d=[1,3,5,7]
1
print("a=",a)
print("b=",b)
print("c=",c)
print("d=",d)
c) Output
a= 3
b= 10.23
c= sample
d= [1, 3, 5, 7]
data type of a= <class 'int'>
data type of b= <class 'float'>
data type of c= <class 'str'>
data type of d= <class 'list'>
2.Read input of different types from user and convert them into
corresponding data types
a) Algorithm
● Start
● Declare variables a, b, c, d with an integer, float, string and list value
respectively.
● Prompt the user to enter an integer, float, string and list values
and store the inputted values to a,b,c and d respectively.
● Print the data type of the variables using type(variable) function.
● Stop
2
b) Code
print("Enter an integer")
a=int(input())
b=float(input())
print("Enter a string")
c=input()
print("Enter a list")
d=list(input())
print(type(a))
print(type(b))
print(type(c))
print(type(d))
c) Output
3
Enter an integer
2.5
Enter a string
Hello world
Enter a list
[a,b,c,d]
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
a) Algorithm
● Start
● Declare two variables a and b to store user input values.
● Prompt the user to enter the two values and store them in a and b
respectively.
● Calculate the sum, difference, product, quotient and remainder using
arithmetic operators and print the results.
● Stop
b) Code
a=float(input())
4
b=float(input())
print("Sum = ",a+b)
print("Difference = ",a-b)
print("Product = ",a*b)
print("Quotient = ",a/b)
print("Remainder = ",a%b)
c) Output
6,4
Sum = 10.0
Difference = 2.0
Product = 24.0
Quotient = 1.5
Remainder = 2.0
4. Find the logarithm of the sum of two numbers taken as input from the
user.
a) Algorithm
● Start
● Import the ‘math’ library in python.
● Declare three variables a,b and sum to store user input values.
● Prompt the user to enter two values and store them in a and b.
● Add the values of a and b and store the result in sum.
● Use log( ) function to find logarithm of the sum and display the result
5
● Stop
b) Code
import math
a=float(input())
b=float(input())
sum=a+b
c) Output
50,50
a) Algorithm
● Start
● Declare a variable num.
● Prompt the user to enter an integer value and store in num.
● If the modulus of num by 2 gives remainder as zero,display that the
number is even.
● Otherwise, if the remainder is not zero, display that the number is odd.
● Stop.
b) Code
print("Enter a number")
6
num=int(input())
if num%2==0:
print(num," is even.")
else:
print(num," is odd.")
c) Output
Enter a number
22
22 is even.
a) Algorithm
● Start
● Declare a variable num to store the user input
● Prompt the user to enter a number and store it in num
● Check if num is greater than 0, and if it is greater than 0 proceed to
further steps, otherwise display that the number is negative.
● If the number is less than or equal to 100 and greater than 50, display
that the number is in between 50 and 100
● If the number is less than 100 and less than or equal to 50, display
that the number is in between 0 and 50
● Stop
b) Code
print("Enter a number")
num=int(input())
if num>=0:
if num<=100:
7
if num>50:
else:
else:
else:
print(num," is negative")
c) Output
Enter a number
25
25 is in between 0 and 50
7. Print the multiplication table of a number given by the user using while
loop
a) Algorithm
● Start
● Declare a variable num to store the value entered by user
● Prompt the user to enter a number
● Initialise a counter variable ‘i’ to the value 1
● Check if i is less than or equal to 10, if true print the value of product
of num and i
● Increment the value of i and go back to the previous step until the
value of i is greater than 10
● Stop
8
b) Code
print("Enter a number")
num=int(input())
i=1
while i<=10:
i=i+1
c) Output
Enter a number
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
9
8. Find the sum of first n natural numbers using loop
a) Algorithm
● Start
● Declare a variable n to store the number up to which sum is to be
found
● Prompt the user to enter the value of n
● Initialize two variables; sum, to store the sum, to zero and i ,as a
counter variable, to 1
● Check if i is less than or equal to n and if true, add the value of sum
to i
● Increment the value of i by 1 until i is greater than n
● Print the value of sum when i greater than na
● Stop
b) Code
n = int(input())
sum=0
i=1
for i in range(n):
sum=sum+i
i+=1
print("Sum = ",sum)
c) Output
10
a) Algorithm
● Start
● Declare variables ‘s’ to store the string inputted by user, ‘ch’ to store
the character to be searched and ‘count’ to store the frequency of the
searched character
● Prompt the user to enter the string and the character whose frequency
is to be found
● Check if each character in the string matches the character inputted
by the user
● When encountering a match, increment count by 1 each time
● Display the frequency of the searched character by printing the value
of count
● Stop
b) Code
s=input()
ch=input()
count=0
for i in s:
Xxx if i==ch:
count+=1
c) Output
entertainment
11
Enter the character to be found
10. Find the factorial of a number using i) loop ii) built-in function iii)
recursion
I.Using Loop
a) Algorithm
● Start
● Declare variables ‘num’, to store user input, ‘factorial’ to store the
result and ‘i’ as counter variable
● Initialise factorial and i to 1
● For each value of i less than or equal to num, multiply the value of i
with factorial and increment i by 1
● Repeat the previous step until i is equal to num and stop once i is
greater than num
● Display the result stored in the variable factorial as the factorial of
the number
● Stop
b) Code
print("Enter a number")
num=int(input())
factorial=1
i=1
for i in range(1,num+1):
factorial*=i
i+=1
12
print("The factorial of the number =",factorial)
c) Output
Enter a number
a) Algorithm
● Start
● Import the math library in python
● Declare a variable num to store user input
● Prompt the user to enter a number and store it in num
● Print the factorial of the number using factorial( ) function in the
math library
● Stop
b) Code
import math
print("Enter a number")
num=int(input())
c) Output
13
Enter a number
III.Using Recursion
a) Algorithm
● Start
● Define a function ‘factorial with parameter n
● If n is 0 or 1, return 1
● Else return n*factorial(n-1)
● Declare variables ‘num’ to store user input and ‘result’ to store value
from function call.
● Prompt the user to enter the value of num
● Using function call statement, store the returned value in result
● Print the result
● Stop
b) Code
def factorial(n):
if n==0:
return 1
else:
return n * factorial(n-1)
print("Enter a number")
num=int(input())
result= factorial(num)
14
print("The factorial of the number = ",result)
c) Output
Enter a number
RESULT:
Familiarised with data types -int, float, string and list, understood and learned
the syntax of if, while and for statements and how to define and call functions.
EXPERIMENT NO. 2
INTRODUCTION TO VECTORISED COMPUTING
AND PLOTTING
AIM:
15
3) Introduction to matplotlib and plots
a) Algorithm:
● Start
● Initialize two python lists with variable number of elements.
● Print the length of each python list using the function len(array_name)
● Print the elements of the initialised list using positive and negative
indexing
● Print a set of elements from the initialised list.
○ Object name[start:stop:step]
○ Start indicates the starting range and the list includes this value.
○ Stop indicates the stop range and the list excludes this value.
○ Step represents the spacing between values
● Concatenate two lists using ‘+’ operator
● Check whether an element is a member of the defined python list.
● Perform iterations for loop and print each element in any if the
defined python list.
● Stop
b) Code:
import numpy as np
a=[1,2,3,4,5,6,7]
print(a[0])
print(a[1])
print(a[2])
print(a[3])
16
print(a[4])
print(a[5])
print(a[6])
print(a[0:6])
print(a[0:7])
print(a[0:7:2])
print(a[0:4:2])
print(a[0:-1])
print(a[3:7])
print(a[6:7])
print(a[1:5:3])
print(a[0:-2])
a=[1,2,3,4,5,6,7]
for i in range(len(a)):
print(i)
print()
for i in range(len(a)):
print(a[i])
print("Length = ",len(a))
print()
17
for i in a:
print(i)
a=[1,2,3,4,5,6,7]
b=[8,9,10,11,12,13,14]
#membership
m=1.33 in a
print(m)
n=10 in b
print(n)
print()
#concatenation
y=a+b
sum=0
for i in range(len(y)):
print(y[i])
sum+=y[i]
print("The sum=",sum)
print()
for i in range(len(a)):
18
print(a[i]+b[i])
c) Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[1, 3, 5, 7]
[1, 3]
[1, 2, 3, 4, 5, 6]
[4, 5, 6, 7]
[7]
[2, 5]
[1, 2, 3, 4, 5]
19
2
22
45
24
243
223
533
34
Length = 7
22
45
24
243
223
533
34
20
False
True
10
11
12
13
14
11
13
15
21
17
19
21
a) Algorithm
● Start
● Import numpy module as np
● Define 1D,2D and 3D arrays.
● Print the dimensions of all the arrays using print(array_name.ndim)
● Use(array_name.shape) to print the number of rows and columns of
all the arrays.
● Print a set of elements from the initialised array.
● Print the rows and columns elements of the 2D array using
array_name[row_index,column_index]
● Concatenate the arrays using the append function
● Perform iteration using for loop and print each element in any of the
defined numpy array
● Perform arithmetic operations such as abs, sin, sinc,etc. And print
zeros and ones matrix
● Stop
b) Code:
import numpy as np
a=np.array([1,2,3])
b=np.array([[1,2,3],[4,5,6],[7,8,9]])
c=np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
22
print(a)
print()
print(b)
print()
print(u)
print()
print("Size of a = ",np.size(a))
print("Shape of a = ",np.shape(a))
print()
print("Size of b = ",np.size(b))
print("Shape of b = ",np.shape(b))
print()
print("Size of c = ",np.size(c))
print("Shape of c = ",np.shape(c))
print()
23
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(a)
print()
print(a[0:1,:])
print()
print(a[1:2,:])
print()
print(a[2:3,:])
print()
print(a[:,0:1])
print()
print(a[:,1:2])
print()
print(a[:,2:3])
print()
print(a[0:2,0:3])
print()
print(a[0:3,0:2])
print()
24
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
b=np.array([[4,5,6],[7,8,9],[10,11,12]])
c=np.array([[-1,2,-3],[-3,-4,5],[6,-7,-8]])
print(np.append(a,b))
print(np.zeros(5))
print(np.ones(5))
print(np.abs(a))
print(np.sin(a))
print(np.sinc(a))
c) Output
[1 2 3]
[[1 2 3]
[4 5 6]
[7 8 9]]
[[[ 1 2 3]
[ 4 5 6]]
25
[[ 7 8 9]
[10 11 12]]]
Dimension of a = 1
Size of a = 3
Shape of a = (3,)
Dimension of b = 2
Size of b = 9
Shape of b = (3, 3)
Dimension of c = 3
Size of c = 12
Shape of c = (2, 2, 3)
[[1 2 3]
[4 5 6]
[7 8 9]]
[[1 2 3]]
[[4 5 6]]
26
[[7 8 9]]
[[1]
[4]
[7]]
[[2]
[5]
[8]]
[[3]
[6]
[9]]
[[1 2 3]
[4 5 6]]
[[1 2]
[4 5]
[7 8]]
[ 1 2 3 4 5 6 7 8 9 4 5 6 7 8 9 10 11 12]
[0. 0. 0. 0. 0.]
27
[1. 1. 1. 1. 1.]
[[1 2 3]
[4 5 6]
[7 8 9]]
a) Algorithm
● Start
● Import numpy as np
● Import matplotlib.pyplot as plt to perform plotting.
● Define another array b using the function np.arange
● Obtain graph of x against y
● Provide proper title and axis labels
● Stop
b) Code
import numpy as np
28
a=np.array([1,1.5,2,2.5,3,3.5,4])
b=np.arange(7)
plt.plot(b,a)
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('sample graph')
plt.savefig('fig1.pdf')
plt.show()
print()
plt.stem(b,a)
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('sample stem')
plt.savefig('fig2.pdf')
plt.show()
c) Output
29
RESULT:
EXPERIMENT NO. 3
SYSTEM OF LINEAR EQUATIONS AND
EIGENVALUES
AIM:
a) Algorithm
30
● Start
● Import numpy as np and linalg from scipy as la
● Create matrix a and vector b.
● Reshape vector b into a column vector b1.
● Compute the determinant of matrix a.
● If the determinant is not zero, the matrix is invertible:
○ Calculate the inverse of matrix a.
○ Multiply the inverse of a by b1 to find the solution vector
x.
○ Print the solution x.
● If the determinant is zero, print "No solution found."
OR
b) Code
import numpy as np
a=np.array([[1,2,3],[0,4,5],[0,0,1]])
b=np.array([1,2,3])
b1=np.reshape(b,(3,1))
if la.det(a)!=0:
31
i=np.array(la.inv(a))
x=i@b1
print('Solution')
print(x)
else:
rank_a=np.linalg.matrix_rank(a)
rows=np.shape(a)[0]
columns=np.shape(a)[1]
x=la.solve(a,b1)
print('Solution')
print(x)
else:
c) Output
Solution
[[-1.5 ]
[-3.25]
[ 3. ]]
32
Solution
[[-1.5 ]
[-3.25]
[ 3. ]]
2) To find eigenvalues, eigenvectors and generate random matrices
a) Algorithm
● Start
● Import numpy as np and linalg as la from scipy
● Create a 3x3 matrix ‘a’ using numpy.
● Use la.eig() from the scipy.linalg module to compute the eigenvalues
and eigenvectors of matrix a.
● Store the result in eig_a.
● Print the entire eig_a tuple, which contains:
○ Eigenvalues of the matrix.
○ Corresponding eigenvectors.
● Print Eigenvalues and Eigenvectors Separately:
○ eig_a[0] contains the eigenvalues.
○ eig_a[1] contains the eigenvectors, which are printed.
● Generate Random Matrices:
○ rand_1: Generate a 2x3 matrix with random float values
between 0 and 1 using np.random.rand(2, 3).
○ rand_2: Generate a 2x3 matrix with random integer
values between 1 and 4 using np.random.randint(1, 5, (2,
3)).
● Print both rand_1 and rand_2.
● Stop
b) Code
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
33
eig_a=la.eig(a)
print(eig_a)
print('\n',eig_a[0])
print('\n',eig_a[1])
rand_1=np.random.rand(2,3)
rand_2=np.random.randint(1,5,(2,3))
print('\n',rand_1)
print('\n',rand_2)
c) Output
(array([ 1.61168440e+01+0.j, -1.11684397e+00+0.j, -1.30367773e-
15+0.j]), array([[-0.23197069, -0.78583024, 0.40824829],
[-0.52532209, -0.08675134, -0.81649658],
[-0.8186735 , 0.61232756, 0.40824829]]))
34
[0.41094141 0.60664534 0.64402541]]
[[1 2 1]
[1 2 3]]
a) Algorithm
● Start
● Create an empty list y to store the maximum absolute eigenvalues.
● Loop to Generate Random Matrices and Compute Eigenvalues:
○ Loop over the range from 1 to 50 (inclusive):
○ For each i, generate an i x i random matrix rand_mat
using np.random.rand(i, i).
○ Compute the eigenvalues of rand_mat using
la.eig(rand_mat)[0].
○ Find the maximum eigenvalue max_eig from the list of
eigenvalues.
○ Compute the absolute value abs_max of this maximum
eigenvalue.
○ Append abs_max to the list y.
● Plot the Maximum Absolute Eigenvalues:
● Create an array x representing the x-axis values (from 0 to 49).
● Plot the data x versus y using plt.plot(x, y).
● Label the x-axis as "x axis" and the y-axis as "y axis".
● Add a title "Eigen Value Sample" to the plot.
● Save the plot as a PDF file named fig1.pdf.
● Display the plot using plt.show().
● Stop
b) Code
import numpy as np
35
y=[]
for i in range(1,51):
rand_mat=np.random.rand(i,i)
eig_mat=la.eig(rand_mat)[0]
max_eig=np.max(eig_mat)
abs_max=np.abs(max_eig)
y.append(abs_max)
x=np.arange(50)
plt.plot(x,y)
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.savefig('fig1.pdf')
plt.show()
c) Output
36
RESULT:
EXPERIMENT NO.4
SINGULAR VALUE DECOMPOSITION
AIM:
37
Using python code to understand the process of singular value decomposition
of a matrix and plot it.
a) Algorithm
● Import required libraries:
○ numpy as np, scipy.linalg as la, and matplotlib.pyplot as plt.
● Prompt the user to input the size of the matrix, N.
● Create a random N x N matrix a using np.random.rand(N, N).
● Perform Singular Value Decomposition (SVD):
○ Compute the Singular Value Decomposition (SVD) of matrix a,
resulting in matrices u, s, and v using la.svd(a).
● Prepare Singular Values Matrix:
○ Convert the vector s of singular values into a diagonal matrix
using np.diag(s).
● Initialize Error Array:
○ Create an empty array error of size N to store the errors for
different approximations.
● Calculate Approximation Errors:
○ For each integer i from 1 to N
○ Compute the absolute value of the difference between the
original matrix and the approximation and store it in.
● Plot and Save Error Analysis:
● Create an array p with values ranging from 0 to N-1.
○ Plot the error values using a stem plot with p on the x-axis and
error on the y-axis.
○ Label the x-axis as 'x axis' and the y-axis as 'y axis'.
○ Then add title 'Error' to the plot.
○ Save the plot as 'fig2.pdf' using plt.savefig('fig2.pdf').
○ Display the plot using plt.show().
● Stop
b) Code
38
import numpy as np
from scipy import linalg as la
print(‘Input the size of the matrix’)
N=int(input())
a=np.random.rand(N,N)
print(a)
u,s,v=la.svd(a)
s=np.diag(s)
error=np.empty(N)
for i in range(1,N+1):
Anew=u[:,0:i]@s[0:i,0:i]@v[0:i,:]
error[i-1]=la.norm(a-Anew)
import matplotlib.pyplot as plt
print(error)
p=np.arange(N)
plt.stem(error,p)
plt.xlabel(‘x axis’)
plt.ylabel(‘y axis’
plt.title(‘Error’)
plt.savefig(‘fig2.pdf’)
plt.show()
c) Output
50
39
[0.39314146 0.66240721 0.20721581 ... 0.60825855 0.35654249 0.07319268]
[0.32893588 0.45232162 0.42729811 ... 0.21318801 0.80854367 0.9297369 ]]
[1.41108125e+01 1.35355494e+01 1.29928912e+01 1.25007418e+01
1.20340612e+01 1.15654729e+01 1.10994599e+01 1.06432855e+01
1.01983242e+01 9.78071216e+00 9.35991585e+00 8.94447773e+00
8.54962109e+00 8.18578074e+00 7.80864696e+00 7.43661084e+00
7.07929883e+00 6.71892440e+00 6.38864548e+00 6.08212920e+00
5.77435896e+00 5.45511570e+00 5.14527107e+00 4.84668838e+00
4.54597837e+00 4.24664795e+00 3.98336890e+00 3.71158478e+00
3.45993514e+00 3.19877082e+00 2.95306731e+00 2.69179148e+00
2.44883685e+00 2.22466844e+00 2.01390820e+00 1.79679559e+00
1.58039634e+00 1.39468381e+00 1.23144393e+00 1.06897899e+00
9.16977771e-01 7.73658205e-01 6.22639141e-01 4.70701602e-01
3.49780916e-01 2.43825794e-01 1.56428402e-01 4.64951756e-02
2.40433297e-02 5.80449423e-14]
RESULT
Understood the singular value decomposition of a matrix and how to plot it
using python.
EXPERIMENT NO. 5
NUMERICAL DIFFERENTIATION AND
INTEGRATION
40
AIM:
a) Algorithm
● Start
● Import necessary libraries
○ numpy for numerical calculations
○ matplotlib.pyplot for plotting.
● Define Time Array:
○ Create an array t using numpy.linspace, which
generates 1000 evenly spaced points between
−2π and 2π.
● Compute Function Values:
○ Compute the values of sine, cosine, sinh, and cosh functions at
each point in the time array t.
○ Store the results in y_sin, x_cos, y_sinh, and x_cosh
respectively.
● Compute Derivatives:
○ Use numpy.gradient to compute the numerical derivatives of
each function.
○ Store the results in y_sin_der, x_cos_der, y_sinh_der, and
x_cosh_der.
● Set Up Subplots:
○ Create a figure and 4x2 grid of subplots using plt.subplots.
○ The first column of plots will show the original functions, and
the second column will show their derivatives.
● Plot Each Function and Its Derivative:
○ For each function (sine, sinh, cosine, cosh):
41
■ Plot the original function in the left column.
■ Plot the derivative in the right column.
■ Set appropriate titles, labels, and grid lines for each
subplot.
● Display the Plots
○ Use plt.show() to display the plot grid with all the subplots.
● Stop
b) Code
import numpy as np
t=np.linspace(-2*np.pi,2*np.pi,1000)
y_sin=np.sin(t)
y_sin_der=np.gradient(y_sin)
y_sinh=np.sinh(t)
y_sinh_der=np.gradient(y_sinh)
x_cos=np.cos(t)
x_cos_der=np.gradient(x_cos)
x_cosh=np.cosh(t)
42
x_cosh_der=np.gradient(x_cosh)
fig,axs=plt.subplots(4,2,constrained_layout=True)
axs[0,0].plot(t,y_sin)
axs[0,0].set_title('Sine wave')
axs[0,0].set(xlabel='time t',ylabel='sine')
axs[0,0].grid()
axs[0,1].plot(t,y_sin_der)
axs[0,1].grid()
axs[1,0].plot(t,y_sinh)
axs[1,0].set_title('Sinh wave')
axs[1,0].set(xlabel='time t',ylabel='sinh')
axs[1,0].grid()
axs[1,1].plot(t,y_sinh_der)
43
axs[1,1].grid()
axs[2,0].plot(t,x_cos)
axs[2,0].set_title('Cosine wave')
axs[2,0].set(xlabel='time t',ylabel='cos')
axs[2,0].grid()
axs[2,1].plot(t,x_cos_der)
axs[2,1].grid()
axs[3,0].plot(t,x_cosh)
axs[3,0].set_title('Cosh wave')
axs[3,0].set(xlabel='time t',ylabel='cosh')
axs[3,0].grid()
axs[3,1].plot(t,x_cosh_der)
axs[3,1].grid()
44
c) Output
a) Algorithm
● Import Necessary Libraries:
○ numpy for numerical calculations.
○ scipy.integrate for numerical integration using Simpson's rule.
○ matplotlib.pyplot for plotting the function.
● Define the Function and Its Analytical Integral:
○ Define the function
○ 𝑓(𝑡)=4𝑡^2+3.
○ Define its integral
○ i(t)= 4/3t +3t for comparison with the numerical method.
45
● Plot the Function:
○ Use numpy.linspace to create a time array from -2 to 2
(correcting its placement).
○ Plot the function using matplotlib and label the axes.
● Calculate the Analytical Area:
○ Find the area under the curve analytically using the integral i(t).
○ Subtract the values at the bounds (-2 to 2) to find the area.
● Apply the Trapezoidal Rule:
○ Use numpy.trapz to compute the area under the curve using the
trapezoidal rule.
○ Calculate the error by taking the absolute difference between the
analytical area and the trapezoidal area.
● Apply Simpson's Rule:
○ Use scipy.integrate.simps to compute the area under the curve
using Simpson's rule.
○ Calculate the error by taking the absolute difference between the
analytical area and the Simpson area.
● Output the Results:
○ Print the calculated areas and the associated errors for both
numerical methods.
b) Code
import numpy as np
def f(t):
return (4*(t**2)+3)
def i(t):
return(4*((t**3)/3)+(3*t))
46
plt.plot(time,f(time))
plt.xlabel('Time(t)')
plt.ylabel('f(t)')
plt.title('Function')
plt.savefig('samplefun.pdf')
plt.show()
area=i(2)-i(-2)
print('Area = ',area)
time=np.linspace(-2,2)
#trapezoidal
area1=np.trapz(f(time),time)
error1=np.abs(area-area1)
#Simpson
area2=intg.simps(f(time),time)
error2=np.abs(area-area2)
47
print('Area using Simpson method = ',area2)
c) Output
Area = 33.33333333333333
Area using Trapezoidal method = 33.351103706788834
Error in Trapezoidal method = 0.01777037345550525
Area using Simpson method = 33.333333333333336
Error in Simpson method = 7.105427357601002e-15
RESULT:
Understood
computing computing derivatives of functions and plotting it and
the integral of functions using analytic, trapezoidal and Simpson’s
method.
48
EXPERIMENT NO. 6
SIMPLE DATA VISUALISATION
AIM:
1) Draw stem plots, line plots, bar plots, and scatter plots and
histogram.
2) Implement and plot the functions f(t)= cos t and f(t)= cos t. cos
5t + cos 5t
1) To draw stem plots, line plots, bar plots, and scatter plots and
histogram
a) Algorithm
● Import libraries: Import numpy for numerical operations and
matplotlib.pyplot for plotting
● Create x-axis: Generate an array x containing 25 evenly spaced
values from 0 to 24.
● Generate random y-axis: Generate an array y containing 25
random floating-point numbers between 0 (inclusive) and 1
(exclusive) using a uniform distribution
● Create line plot
○ Plot the data points x and y using plt.plot.
○ Label the x-axis and y-axis using plt.xlabel and
plt.ylabel. Add a title to the plot using plt.title.
○ Save the plot as "Fig1.pdf" using plt.savefig.
○ Display the plot using plt.show.
● Generate and Plot Random Data (Stem Plot)
○ Plot the data points x and y using plt.stem. This
emphasises individual data points.
○ Label axes and add title: Label the x-axis and y-axis
using plt.xlabel and plt.ylabel. Add a title to the plot
using plt.title.
○ Save the plot as “Fig2.pdf” and display the plot using
plt.show
49
● Generate and Plot Random Data (Scatter Plot)
○ Create scatter plot: Plot the data points x and y using
plt.scatter. This shows the relationship between
individual data points.
○ Label axes and add title: Label the x-axis and y-axis
using plt.xlabel and plt.ylabel. Add a title to the plot
using plt.title.
○ Save the plot as “Fig3.pdf” and display the plot using
plt.show
b) Code
import numpy as np
x=np.arange(25)
y=np.random.rand(25)
plt.plot(x,y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')
plt.savefig('Fig1.pdf')
plt.show()
plt.stem(x,y)
50
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Stem Plot')
plt.savefig('Fig2.pdf')
plt.show()
plt.scatter(x,y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot')
plt.savefig('Fig3.pdf')
plt.show()
plt.boxplot(y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Box Plot')
plt.savefig('Fig4.pdf')
plt.show()
plt.bar(x,y)
plt.xlabel('X-axis')
51
plt.ylabel('Y-axis')
plt.title('Bar Plot')
plt.savefig('Fig5.pdf')
plt.show()
plt.hist(y)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Histogram')
plt.savefig('Fig6.pdf')
plt.show()
c) Output
52
2) Implement and plot the functions f(t)= cos t and f(t)= cos t. cos 5t + cos
5t
a) Algorithm
● Import Libraries:
○ Import numpy for numerical operations.
○ Import matplotlib.pyplot for plotting.
● Create Time Array:
○ Generate an array t containing values from -10 to 10
(inclusive) with a step size of 0.01 . This creates a high-
resolution time axis for the plot.
● Calculate Functions:
○ Calculate the cosine of t and store it in the array cos_t
using np.cos(t).
○ Define a new function ft by combining cosine terms:
○ ft = np.cos(t) * np.cos(5*t) + np.cos(5*t).
○ This combines two cosine terms: one with frequency 1
and another with frequency 5.
53
● Create the Plot:
○ Plot the function ft with a black line using plt.plot(t, ft,
color='black').
○ Plot the reference cosine function (cos_t) with a red line
for comparison using plt.plot(t, cos_t, color='red').
○ Label the x-axis and y-axis using plt.xlabel and
plt.ylabel.
○ Add a legend to distinguish the lines using
plt.legend(['F(t)', 'Cos(t)']). This clarifies which line
represents ft and cos_t.
○ Add a title to the plot using plt.title('Function Plot of').
○ Save and Display the Plot:
■ Save the plot as "Fig1.pdf" using
plt.savefig('Fig1.pdf')
■ Display the plot using plt.show().
b) Code
import numpy as np
t= np.arange(-10,11,0.01)
cos_t=np.cos(t)
ft= np.cos(t)*np.cos(5*t)+np.cos(5*t)
plt.plot(t,ft, color='black')
plt.plot(t,cos_t, color='red')
plt.xlabel('X-axis')
54
plt.ylabel('Y-axis')
plt.legend(['F(t)','Cos(t)'])
plt.savefig('Fig1.pdf')
plt.show()
c) Output
55
RESULT:
● Various types of plots - stem, line, bar and scatter have been familiarised.
● f(t) = cos t and f(t) = cos t.cos 5t +cos5t have been implemented and plotted.
EXPERIMENT NO. 7
DATA ANALYSIS
AIM:
ii) Compute mean and standard deviation of the signal, plot its
histogram
PROGRAMS
a) Algorithm
56
● Import numpy for numerical operations and matplotlib.pyplot
for plotting.
● Read data from CSV file:
○ Use np.genfromtxt to read the "Volt.csv" file, assuming a
comma delimiter.
○ Extract voltage and time data from the CSV, skipping
header rows if present.
● Plot voltage vs. time:
○ Create a line plot using plt.plot(time, volt).
○ Set appropriate labels for x-axis ("Time"), y-axis
("Voltage"), and title ("Voltage vs. Time").
○ Save the plot as "Fig1.pdf" and display it.
● Calculate and print voltage statistics:
○ Calculate the mean and standard deviation of voltage
using np.mean(volt) and np.std(volt), respectively.
○ Print the calculated values.
● Plot voltage histogram:
○ Create a histogram of the voltage data with 25 bins and
black edges using plt.hist(volt, bins=25,
edgecolor='black').
○ Set appropriate labels and title for the histogram.
○ Save the histogram as "Fig2.pdf" and display it.
● Calculate and print time statistics:
○ Calculate the mean and standard deviation of time using
np.mean(time) and np.std(time), respectively.
○ Print the calculated values.
● Plot time histogram:
○ Create a histogram of the time data with 25 bins and
black edges.
○ Set appropriate labels and title for the time histogram.
○ Save the histogram as "Fig3.pdf" and display it.
b) Code
57
import numpy as np
csv=np.genfromtxt("Volt.csv",delimiter=',')
volt=csv[2:27,1:2]
time=csv[2:27,2:3]
plt.plot(time,volt)
plt.xlabel('Time')
plt.ylabel('Voltage')
plt.savefig('Fig1.pdf')
plt.show()
c) Output
58
Mean voltage = 11.48
Standard Deviation = 6.664052820919114
2) Compute mean and standard deviation of the signal, plot its histogram
a) Algorithm
● Calculate and print voltage statistics:
○ Calculate the mean and standard deviation of voltage
using np.mean(volt) and np.std(volt), respectively.
○ Print the calculated values.
● Plot voltage histogram:
○ Create a histogram of the voltage data with 25 bins and
black edges using plt.hist(volt, bins=25,
edgecolor='black').
○ Set appropriate labels and title for the histogram.
○ Save the histogram as "Fig2.pdf" and display it.
● Calculate and print time statistics:
○ Calculate the mean and standard deviation of time using
np.mean(time) and np.std(time), respectively.
○ Print the calculated values.
● Plot time histogram:
○ Create a histogram of the time data with 25 bins and
black edges.
59
○ Set appropriate labels and title for the time histogram.
○ Save the histogram as "Fig3.pdf" and display it.
b) Code
import numpy as np
mean_volt=np.mean(volt)
sd_v=np.std(volt)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Voltage Histogram')
plt.savefig('Fig2.pdf')
plt.show()
mean_time=np.mean(time)
sd_t=np.std(time)
60
print('Mean time = ',mean_time)
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Time Histogram')
plt.savefig('Fig3.pdf')
plt.show()
c) Output
61
RESULT:
● A.csv file with multiple columns of numerical entries has been read as a
numpy array.
● Histogram of entries in a given column was plotted.
● The mean and standard deviation of entries in a given column was
calculated.
EXPERIMENT NO. 8
SOLUTION OF ORDINARY DIFFERENTIAL
EQUATIONS
AIM:
(i) Solve the first order differential equation 𝑑𝑥/𝑑𝑡 + 2𝑥 = 0 with the
initial condition 𝑥(0) = 1
62
(ii) Solve the second order differential equation d 2x/dt2+ 2 𝑑𝑥/𝑑𝑡 +
2𝑥 = 𝑒-t with initial condition (0,1)
(i) Solve the equation for the transient current through the RC circuit
with initial current 5A that is driven by
1) 5V 2) 5𝑒-t𝑢(𝑡)
(ii) Solve the equation of transient current through a RLC circuit with
R=1 ohm, L=1 mHandC=1μF that is driven by
1) 5V 2) 5𝑒-t 𝑢(𝑡)
PROGRAMS:
a) Algorithm
● Start
● Import the numpy module as np, matplotlib.pyplot module as
plt, and odeint function from scipy.integrate module.
● Define a function f with x and t as parameters, which returns
the value-2*x 4. The initial condition x0 is assigned as
● Using the function np.linspace, initialise the time points t as a
numpy array (0,5) with 100 intervals.
● Solve the ordinary differential equation using the function
odeint with f, x0, and t as arguments, to obtain x as result.
● With appropriate title, legend and axis labels, plot x against t.
● Stop
b) Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def f(x, t):
return-2*x
63
x0 = 1
t = np.linspace(0, 5, 100)
x =odeint(f, x0, t)
plt.plot(t,x, label="x(t) = e^(-2t)")
plt.title("Graph of x(t)") plt.xlabel("t") plt.ylabel("x(t)")
plt.legend()
plt.grid()
plt.show()
c) Output
64
a) Algorithm
● Start
● Import the numpy module as np, matplotlib.pyplot module as
plt, and odeint function from scipy.integrate module
● Define a function equation with y and t as parameters which
returns two values dxdt and d2xdt2 , where dxdt is assigned as
y[1] (which is dx/dt) and d2xdt2 is assigned as-2 * dxdt- 2 * x +
np.exp(-t). These two values are returned
● The initial condition x0 is assigned as [0,1]
● Using the function np.linspace, initialise the time points t as a
numpy array (0,5) with 100 intervals.
● Solve the ordinary differential equation using the function
odeint with equation, x0, and t as arguments, to obtain x and
dx/dt as result.
● By appropriate slicing, plot the graph of x against t and dx/dt
against t. Provide proper legend, x label, y label and title.
● Stop
b) Code
import numpy as np
t = np.linspace(0, 5, 100)
x =odeint(equation, x0, t)
65
plt.title("Graph of x(t)")
plt.xlabel("t")
plt.ylabel("x(t)")
plt.legend()
plt.grid()
plt.show()
c) Output
I) Solve the equation for the transient current through the RC circuit
with initial current 5A that is driven by (i) 5V
66
a) Algorithm
● Start
● Import the numpy module as np, matplotlib module as plt, and
odeint function from scipy.integrate module
● Initialise RC = 3
● Define a function f with i and t as parameters, which returns a
value dxdt, where dxdt is assigned as-i/RC
● Using the function np.linspace, initialise the time points t as a
numpy array (0,10) with 100 intervals.
● Solve the ordinary differential equation using the function
odeint with f, i0, and t as arguments, to obtain i as result.
● With appropriate title, legend and axis labels, plot transient
current i against t
● Stop
b) Code
import numpy as np
RC=3
dxdt =-(i/RC)
return dxdt
i0 = 5
i = odeint(f, i0, t)
plt.title("Graph of i(t)")
67
plt.xlabel("t")
plt.ylabel("i(t)")
plt.legend()
plt.grid()
plt.show()
c) Output
II) Solve the equation for the transient current through the RC circuit
with initial current 5A that is driven by 5𝑒-t𝑢(𝑡)
a) Algorithm
● Start
● Import the numpy module as np, matplotlib module as plt,and
odeint function from scipy.integrate module.
● Initialise R=1 and C=10-6
● Define a function f with i and t as parameters,which returns
dxdt, where dxdt is assigned value–i/𝑅𝐶−5 𝑒-t/R
● Using the function np.linspace,initialise the time points t as a
numpy array (0,10-5) with 100 intervals
● The initial condition i0 is assigned as 5.
● Solve the ordinary differential equation using the function
odeint with f,i0,and as arguments,to obtain i as result
68
● With appropriate title,legend and axis labels, plot transient
current against t.
● Stop
b) Code
importnumpyasnp
fromscipy.integrateimportodeint
importmatplotlib.pyplotasplt
R=1
C=10**-6
deff(i,t):
dxdt=-((5*np.exp(-t)/R)+(i/(R*C)))
returndxdt
t=np.linspace(0,10**-5,100)
i0=5
i=odeint(f,i0,t)
plt.plot(t,i,label="i(t)inV=5e^-t")
plt.title("Graphofi(t)")
plt.xlabel("t")
plt.ylabel("i(t)")
plt.legend()
plt.grid()
plt.show()
69
c) Output
III) Solve the equation of transient current through a RLC circuit with
R=1 ohm, L=1 mHandC=1μFthat is driven by : (i) 5V , (ii) 5𝑒-t 𝑢(𝑡)
a) Algorithm
● Start
● Import the numpy module as np, matplotlib module as plt, and
odeint function from scipy.integrate module.
● Initialise R = 1, L= 10-3 , and C = 10-6
● Define two functions v_func_constant and v_func_exponential
for the two cases.
○ Both functions will have t as the parameter and returns
the value 5 and 5*e-t respectively
● Define a function rlc_circuit with i, t, v_func as parameters and
returns two values didt and d2idt2.
○ didt is assigned as i[1] and d2idt2 is assigned the value-
v_func(t)- (R/L) * didt- (1/(L*C)) * i[0])
70
● Using the function np.linspace, initialise the time points t as a
numpy array (0,0.01) with 1000 intervals.
● The initial condition i0 is assigned as [0,5]
● Solve the differential equations
○ For the circuit driven by 5V supply, use the function
odeint withrlc_circuit, i0, t and v_func_constant as
arguments to obtain i_constant.
○ For the circuit driven by 5𝑒-t𝑢(𝑡), use the function odeint
with rlc_circuit, i0, t and v_func_exponential as
arguments to obtain i_exponential
● With appropriate title, legend, xlabel and ylabel, plot the graph
of transient current i against time for both the cases.
● Stop
b) Code
importnumpyasnp
fromscipy.integrateimportodeint
importmatplotlib.pyplotasplt
R=1
L=1e-3
C=1e-6
defrlc_circuit(i,t,v_func):
didt=i[1]
d2idt2=(-v_func(t)-(R/L)*didt-(1/(L*C))*i[0])
return[didt,d2idt2]
defv_func_constant(t):
return5
defv_func_exponential(t):
71
return5*np.exp(-t)
t=np.linspace(0,0.01,1000)
i0=[0,5]
i_constant=odeint(rlc_circuit,i0,t,args=(v_func_constant,))
i_exponential=odeint(rlc_circuit,i0,t,args=(v_func_exponential,
))
fig,(ax1,ax2)=plt.subplots(2,1,constrained_layout='True',
figsize=(10,6))
ax1.set_ylabel("Current (A)")
ax1.legend()
ax1.grid(True)
alpha=0.8)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Current (A)")
ax2.legend()
ax2.grid(True)
plt.show()
c) Output
72
RESULT:
73
EXPERIMENT NO. 9
CONVERGENCE OF FOURIER SERIES
AIM:
i) Realise the Fourier series f(t) with the vector t= [-10,10], T=20 for
n=3,5,10,100 terms and observe the lack of convergence at the points of
discontinuity.
PROGRAMS:
1) Realise the Fourier Series with the vector t=[-10,10] and T=20 for
n=3,5,10,100 terms and observe the lack of convergence at the points of
discontinuity.
a) Algorithm
● Start
● Import numpy module as np and matplotlib.pyplot as plt
● Initialise t as [-10,10] with 1000 intervals using
np.linspace(start,stop,interval)
● Initialise T=20
74
● Define a function fourier_series with t, T and n as arguments to
compute the Fourier series.
○ Initialise an array f_t of zeros with the same length as t
○ Run a for loop from i=0 to n-1. For each iteration,
compute the cosine term, ((-1i) /(2i+1))*
(cos((2i+1)*2𝜋*(t/T))) and add this term to f_t . After
the end of the loop, return the value of (4/𝜋)*f_t 6. Use a
for loop to compute the Fourier series for each value of n
(number of terms) and plot the result.
● Provide appropriate x label, y label title, legend and display the
graph
● Stop
b) Code
import numpy as np
T =20
f_t = np.zeros(len(t))
for i in range(n):
f = fourier_series(t, T, n)
plt.xlabel('t')
75
plt.ylabel('f(t)')
plt.legend()
plt.grid()
plt.show()
c) Output
a) Algorithm
● Start
● Import the numpy module as np
● Define a function madhava_series with t,T and n as arguments
to
calculate the Madhava series
● Initialise f_t as 0
● Run a for loop in the
range i=0 to n-1. For each iteration,
calculate the term ((-1i) /(2i+1))* (cos((2i+1)*2𝜋*(t/T))) and
add this term to f_t . Return the value of 4*f_t
● Make the value of t=0 and T=20
76
● Run a for loop to iterate over values of n=3,5,10,100,100000
and 10000000. For each n, call the function madhava_series
● Calculate the value of 𝜋 for each value of n and print the value
● Stop
b) Code
import numpy as np
f_t = 0
for i in range(n):
np.cos((2*i + 1) * 2 * np.pi * t / T)
return 4 * f_t
t=0
T = 20
f = madhava_series(t, T, n)
c) Output
n= 3: pi = 3.466666666666667
n= 5: pi = 3.3396825396825403
n= 10: pi =3.0418396189294032
n= 100: pi = 3.1315929035585537
n= 100000: pi = 3.1415826535897198
n= 10000000: pi = 3.1415925535897915
77
RESULT:
● Realised the Fourier series f(t) with the vector t=[-10,10], T=20 for
n=3,5,10,100,100000 terms and observed the lack of convergence at the
points of discontinuity.
𝑓(𝑡) = 4/𝑐 [ (1 − 1/ 3 𝑜𝑠 (2𝑡 3𝑇/ 𝑐 ) + 1/ 5 𝑜𝑠 ( 2𝑡 5𝑇/𝑐 ) − 1/7 𝑜𝑠
(2𝑡 7𝑇/𝑇)
⋯ + ⋯]
● With t made as a zero vector , f(0)=1, resulting in the Madhava series
for 𝜋
and computed the value of 𝜋 for the first 3, 5, 10, 100, 100000,10000000
terms
π = 4[1- (1/3) + (1/5) - (1/7) + …..]
78