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 [Link] 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'>
[Link] 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
[Link] 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
[Link] 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[Link])
print(a[Link])
print(a[0:-1])
print(a[3:7])
print(a[6:7])
print(a[Link])
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=[Link]([1,2,3])
b=[Link]([[1,2,3],[4,5,6],[7,8,9]])
c=[Link]([[[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 = ",[Link](a))
print("Shape of a = ",[Link](a))
print()
print("Size of b = ",[Link](b))
print("Shape of b = ",[Link](b))
print()
print("Size of c = ",[Link](c))
print("Shape of c = ",[Link](c))
print()
23
a=[Link]([[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=[Link]([[1,2,3],[4,5,6],[7,8,9]])
b=[Link]([[4,5,6],[7,8,9],[10,11,12]])
c=[Link]([[-1,2,-3],[-3,-4,5],[6,-7,-8]])
print([Link](a,b))
print([Link](5))
print([Link](5))
print([Link](a))
print([Link](a))
print([Link](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 [Link] as plt to perform plotting.
● Define another array b using the function [Link]
● Obtain graph of x against y
● Provide proper title and axis labels
● Stop
b) Code
import numpy as np
28
a=[Link]([1,1.5,2,2.5,3,3.5,4])
b=[Link](7)
[Link](b,a)
[Link]('x axis')
[Link]('y axis')
[Link]('sample graph')
[Link]('[Link]')
[Link]()
print()
[Link](b,a)
[Link]('x axis')
[Link]('y axis')
[Link]('sample stem')
[Link]('[Link]')
[Link]()
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=[Link]([[1,2,3],[0,4,5],[0,0,1]])
b=[Link]([1,2,3])
b1=[Link](b,(3,1))
if [Link](a)!=0:
31
i=[Link]([Link](a))
x=i@b1
print('Solution')
print(x)
else:
rank_a=[Link].matrix_rank(a)
rows=[Link](a)[0]
columns=[Link](a)[1]
x=[Link](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 [Link]() from the [Link] 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 [Link](2, 3).
○ rand_2: Generate a 2x3 matrix with random integer
values between 1 and 4 using [Link](1, 5, (2,
3)).
● Print both rand_1 and rand_2.
● Stop
b) Code
a=[Link]([[1,2,3],[4,5,6],[7,8,9]])
33
eig_a=[Link](a)
print(eig_a)
print('\n',eig_a[0])
print('\n',eig_a[1])
rand_1=[Link](2,3)
rand_2=[Link](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 [Link](i, i).
○ Compute the eigenvalues of rand_mat using
[Link](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 [Link](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 [Link].
● Display the plot using [Link]().
● Stop
b) Code
import numpy as np
35
y=[]
for i in range(1,51):
rand_mat=[Link](i,i)
eig_mat=[Link](rand_mat)[0]
max_eig=[Link](eig_mat)
abs_max=[Link](max_eig)
[Link](abs_max)
x=[Link](50)
[Link](x,y)
[Link]('x axis')
[Link]('y axis')
[Link]('[Link]')
[Link]()
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, [Link] as la, and [Link] as plt.
● Prompt the user to input the size of the matrix, N.
● Create a random N x N matrix a using [Link](N, N).
● Perform Singular Value Decomposition (SVD):
○ Compute the Singular Value Decomposition (SVD) of matrix a,
resulting in matrices u, s, and v using [Link](a).
● Prepare Singular Values Matrix:
○ Convert the vector s of singular values into a diagonal matrix
using [Link](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 '[Link]' using [Link]('[Link]').
○ Display the plot using [Link]().
● 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=[Link](N,N)
print(a)
u,s,v=[Link](a)
s=[Link](s)
error=[Link](N)
for i in range(1,N+1):
Anew=u[:,0:i]@s[0:i,0:i]@v[0:i,:]
error[i-1]=[Link](a-Anew)
import [Link] as plt
print(error)
p=[Link](N)
[Link](error,p)
[Link](‘x axis’)
[Link](‘y axis’
[Link](‘Error’)
[Link](‘[Link]’)
[Link]()
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
○ [Link] for plotting.
● Define Time Array:
○ Create an array t using [Link], 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 [Link] 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 [Link].
○ 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 [Link]() to display the plot grid with all the subplots.
● Stop
b) Code
import numpy as np
t=[Link](-2*[Link],2*[Link],1000)
y_sin=[Link](t)
y_sin_der=[Link](y_sin)
y_sinh=[Link](t)
y_sinh_der=[Link](y_sinh)
x_cos=[Link](t)
x_cos_der=[Link](x_cos)
x_cosh=[Link](t)
42
x_cosh_der=[Link](x_cosh)
fig,axs=[Link](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.
○ [Link] for numerical integration using Simpson's rule.
○ [Link] 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 [Link] 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 [Link] 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 [Link] 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
[Link](time,f(time))
[Link]('Time(t)')
[Link]('f(t)')
[Link]('Function')
[Link]('[Link]')
[Link]()
area=i(2)-i(-2)
print('Area = ',area)
time=[Link](-2,2)
#trapezoidal
area1=[Link](f(time),time)
error1=[Link](area-area1)
#Simpson
area2=[Link](f(time),time)
error2=[Link](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
[Link] 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 [Link].
○ Label the x-axis and y-axis using [Link] and
[Link]. Add a title to the plot using [Link].
○ Save the plot as "[Link]" using [Link].
○ Display the plot using [Link].
● Generate and Plot Random Data (Stem Plot)
○ Plot the data points x and y using [Link]. This
emphasises individual data points.
○ Label axes and add title: Label the x-axis and y-axis
using [Link] and [Link]. Add a title to the plot
using [Link].
○ Save the plot as “[Link]” and display the plot using
[Link]
49
● Generate and Plot Random Data (Scatter Plot)
○ Create scatter plot: Plot the data points x and y using
[Link]. This shows the relationship between
individual data points.
○ Label axes and add title: Label the x-axis and y-axis
using [Link] and [Link]. Add a title to the plot
using [Link].
○ Save the plot as “[Link]” and display the plot using
[Link]
b) Code
import numpy as np
x=[Link](25)
y=[Link](25)
[Link](x,y)
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Line Plot')
[Link]('[Link]')
[Link]()
[Link](x,y)
50
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Stem Plot')
[Link]('[Link]')
[Link]()
[Link](x,y)
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Scatter Plot')
[Link]('[Link]')
[Link]()
[Link](y)
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Box Plot')
[Link]('[Link]')
[Link]()
[Link](x,y)
[Link]('X-axis')
51
[Link]('Y-axis')
[Link]('Bar Plot')
[Link]('[Link]')
[Link]()
[Link](y)
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Histogram')
[Link]('[Link]')
[Link]()
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 [Link] 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 [Link](t).
○ Define a new function ft by combining cosine terms:
○ ft = [Link](t) * [Link](5*t) + [Link](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 [Link](t, ft,
color='black').
○ Plot the reference cosine function (cos_t) with a red line
for comparison using [Link](t, cos_t, color='red').
○ Label the x-axis and y-axis using [Link] and
[Link].
○ Add a legend to distinguish the lines using
[Link](['F(t)', 'Cos(t)']). This clarifies which line
represents ft and cos_t.
○ Add a title to the plot using [Link]('Function Plot of').
○ Save and Display the Plot:
■ Save the plot as "[Link]" using
[Link]('[Link]')
■ Display the plot using [Link]().
b) Code
import numpy as np
t= [Link](-10,11,0.01)
cos_t=[Link](t)
ft= [Link](t)*[Link](5*t)+[Link](5*t)
[Link](t,ft, color='black')
[Link](t,cos_t, color='red')
[Link]('X-axis')
54
[Link]('Y-axis')
[Link](['F(t)','Cos(t)'])
[Link]('[Link]')
[Link]()
c) Output
55
RESULT:
● Various types of plots - stem, line, bar and scatter have been familiarised.
● f(t) = cos t and f(t) = cos [Link] 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 [Link]
for plotting.
● Read data from CSV file:
○ Use [Link] to read the "[Link]" 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 [Link](time, volt).
○ Set appropriate labels for x-axis ("Time"), y-axis
("Voltage"), and title ("Voltage vs. Time").
○ Save the plot as "[Link]" and display it.
● Calculate and print voltage statistics:
○ Calculate the mean and standard deviation of voltage
using [Link](volt) and [Link](volt), respectively.
○ Print the calculated values.
● Plot voltage histogram:
○ Create a histogram of the voltage data with 25 bins and
black edges using [Link](volt, bins=25,
edgecolor='black').
○ Set appropriate labels and title for the histogram.
○ Save the histogram as "[Link]" and display it.
● Calculate and print time statistics:
○ Calculate the mean and standard deviation of time using
[Link](time) and [Link](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 "[Link]" and display it.
b) Code
57
import numpy as np
csv=[Link]("[Link]",delimiter=',')
volt=csv[2:27,1:2]
time=csv[2:27,2:3]
[Link](time,volt)
[Link]('Time')
[Link]('Voltage')
[Link]('[Link]')
[Link]()
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 [Link](volt) and [Link](volt), respectively.
○ Print the calculated values.
● Plot voltage histogram:
○ Create a histogram of the voltage data with 25 bins and
black edges using [Link](volt, bins=25,
edgecolor='black').
○ Set appropriate labels and title for the histogram.
○ Save the histogram as "[Link]" and display it.
● Calculate and print time statistics:
○ Calculate the mean and standard deviation of time using
[Link](time) and [Link](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 "[Link]" and display it.
b) Code
import numpy as np
mean_volt=[Link](volt)
sd_v=[Link](volt)
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Voltage Histogram')
[Link]('[Link]')
[Link]()
mean_time=[Link](time)
sd_t=[Link](time)
60
print('Mean time = ',mean_time)
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Time Histogram')
[Link]('[Link]')
[Link]()
c) Output
61
RESULT:
● [Link] 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, [Link] module as
plt, and odeint function from [Link] 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 [Link], 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 [Link] as plt
from [Link] import odeint
def f(x, t):
return-2*x
63
x0 = 1
t = [Link](0, 5, 100)
x =odeint(f, x0, t)
[Link](t,x, label="x(t) = e^(-2t)")
[Link]("Graph of x(t)") [Link]("t") [Link]("x(t)")
[Link]()
[Link]()
[Link]()
c) Output
64
a) Algorithm
● Start
● Import the numpy module as np, [Link] module as
plt, and odeint function from [Link] 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 +
[Link](-t). These two values are returned
● The initial condition x0 is assigned as [0,1]
● Using the function [Link], 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 = [Link](0, 5, 100)
x =odeint(equation, x0, t)
65
[Link]("Graph of x(t)")
[Link]("t")
[Link]("x(t)")
[Link]()
[Link]()
[Link]()
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 [Link] 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 [Link], 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)
[Link]("Graph of i(t)")
67
[Link]("t")
[Link]("i(t)")
[Link]()
[Link]()
[Link]()
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 [Link] 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 [Link],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
[Link]
[Link]
R=1
C=10**-6
deff(i,t):
dxdt=-((5*[Link](-t)/R)+(i/(R*C)))
returndxdt
t=[Link](0,10**-5,100)
i0=5
i=odeint(f,i0,t)
[Link](t,i,label="i(t)inV=5e^-t")
[Link]("Graphofi(t)")
[Link]("t")
[Link]("i(t)")
[Link]()
[Link]()
[Link]()
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 [Link] 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 [Link], 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
[Link]
[Link]
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*[Link](-t)
t=[Link](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)=[Link](2,1,constrained_layout='True',
figsize=(10,6))
ax1.set_ylabel("Current (A)")
[Link]()
[Link](True)
alpha=0.8)
ax2.set_xlabel("Time (s)")
ax2.set_ylabel("Current (A)")
[Link]()
[Link](True)
[Link]()
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 [Link] as plt
● Initialise t as [-10,10] with 1000 intervals using
[Link](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 = [Link](len(t))
for i in range(n):
f = fourier_series(t, T, n)
[Link]('t')
75
[Link]('f(t)')
[Link]()
[Link]()
[Link]()
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):
[Link]((2*i + 1) * 2 * [Link] * 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