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

Comp Phy Lab

The document outlines a series of experiments for a Computational Physics course, focusing on data visualization and linear algebra using Python and the NumPy library. Each experiment includes an aim, requirements, Python code, algorithms, and precautions for tasks such as plotting graphs, vector operations, matrix multiplication, and solving linear equations. The experiments are designed to enhance practical understanding of computational techniques in physics and engineering.

Uploaded by

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

Comp Phy Lab

The document outlines a series of experiments for a Computational Physics course, focusing on data visualization and linear algebra using Python and the NumPy library. Each experiment includes an aim, requirements, Python code, algorithms, and precautions for tasks such as plotting graphs, vector operations, matrix multiplication, and solving linear equations. The experiments are designed to enhance practical understanding of computational techniques in physics and engineering.

Uploaded by

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

Computational Physics

Course Code: PHY1003


Experimental Record
Slot: B23+D21+D22

Submitted by:
NAME: Kartikey Singh
REG No.: 24BCE11116
Bachelor of Technology
In
Computer Science & Engineering

Submitted To:
Dr. Vayunandana Kishore.P
SCHOOL OF COMPUTER SCIENCE And
ENGINEERING
S.No. TOPIC NAME

1. Plot a line graph

2. Plot a pie chart.

3. Plot a parabola.

4. Plot a bar graph.

5. Program to add/subtract two vectors.

6. Program to find dot product of two


vectors.
7. Program to find multiply two square
matrices of any order.

8. Program to find inverse of 3x3 matrix.

9. Program to find eigen values of a 3x3


matrix.

10. Program to solve linear equations


containing 3 variables.
EXPERIMENT 1:

AIM: To Plot a Line Graph in python

REQUIREMENTS:
 Libraries to be used: Matplot Library is used for data
visualization
 Python version to be used: Python 3.x or above.

Python Code:

import matplotlib.pyplot as plt


#Define data
X = [1,2,3,4,5]
Y = [2,4,6,8,10]

#Create line graph


plt.plot(x,y)
#Label the graph
plt.title('Line Graph Example')

plt.xlabel('X-Label')
plt.ylabel('Y-label')

#Show the graph


plt.show()
ALGORITHM:
1. Start
2. Import matplotlib.pyplot library.
3. Define data for X and Y axes
4. Use plt.plot() to create a line graph
6. Label the graph
7. Display the graph
8. End

OUTPUT:
EXPERIMENT 2:

AIM: Plot a pie chart in python.

REQUIREMENTS:
 Libraries to be used: Matplot Library is used for
data visualization.
 Python version to be used: Python 3.x or above.

Python Code:

import matplotlib.pyplot as plt

#Step 1: Define Data and labels


values= [30,25,20,25]
labels= ['Category A', 'Category B','Category C’
,'Category D']

#Step 2: Create the pie chart


plt.pie(values,labels=labels,autopct='%1.2f%%')

#Step 3: Label the chart


plt.title('Pie chart Example')
plt.show()
ALGORITHM:

i. Start
ii. Import matplotlib.pyplot library
iii. Define data and labels for the chart
iv. Use plt.pie() to create a pie chart
v. Label the chart
vi. Display the chart
vii. End

:
OUTPUT:
EXPERIMENT 3:

AIM: To plot a parabola in python.

REQUIREMENTS:
 Libraries to be used: Matplot Library is used for
data visualization.
 NumPy library for range of X-Values
 Python version to be used: Python 3.x or above.

Python Code:
import matplotlib.pyplot as plt
import numpy as np

#Define range of X values


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

#Calulate Y- Values
y=x**2

#Plotting the parabola and Labelling the graph


plt.plot(x , y)
plt.title('A parabola')
plt.xlabel('X values')
plt.ylabel('Y values')

#Print the Graph


plt.show()
ALGORITHM:

i. Start
ii. Import matplotlib.pyplot library
iii. Define categories and corresponding values
iv. Use plt.bar() to create a bar graph
v. Label the graph
vi. Display the bar graph
vii. End

OUTPUT:
EXPERIMENT 4:

AIM: Program to plot a bar graph in python.

REQUIREMENTS:
 Python version to be used: Python 3.x or above
 Libraries to be used: Matplot Library is used for
data visualization.

Python Code:

import matplotlib.pyplot as plt


# Step 1: Define categories and values
categories = ["A","B","C","D"]
values = [5,7,19,2]

#Create bar graph


plt.bar(categories,values)

#Label the graph


plt.title("Bar graph Example")
plt.xlabel("Categories")
plt.ylabel("Values")

#Show the graph


plt.show()
ALGORITHM:
i. Start
ii. Import matplotlib.pyplot library
iii. Define categories and corresponding values
iv. Use plt.bar() to create a bar graph
v. Label the graph
vi. Display the bar graph
vii. End

OUTPUT:
EXPERIMENT 5:

AIM: Program to add/subtract two vectors.

REQUIREMENTS:
 Libraries to be used: Numpy for array calculations.
 Python version to be used: Python 3.x or above.

Python Code:

import numpy as np
def add_vectors(vector1, vector2):
if vector1.shape != vector2.shape:
raise ValueError("Vectors must have the same dimension.")
else:
return vector1 + vector2

def subtract_vectors(vector1, vector2):


if vector1.shape != vector2.shape:
raise ValueError("Vectors must have the same dimension.")
else:
return vector1 - vector2

# Example usage:
vector1 = np.array([1, 2, 3])
vector2 = np.array([4, 5, 6])

result_sum = add_vectors(vector1, vector2)


result_difference = subtract_vectors(vector1, vector2)

print("Sum of vectors:", result_sum)


print("Difference of vectors:", result_difference)
ALGORITHM:
1. Import NumPy: Import the NumPy library for efficient
array operations.
2. Define Functions:
o add_vectors(vector1, vector2):
 Check if the dimensions of both vectors are the same.
 Add corresponding elements of both vectors and store the
result in a new vector.
 Return the new vector.
o subtract_vectors(vector1, vector2):
 Check if the dimensions of both vectors are the same.
 Subtract corresponding elements of the second vector
from the first vector and store the result in a new
vector.
 Return the new vector.
3. Create Vectors: Define two vectors as NumPy arrays.
4. Perform Operations:
o Call the add_vectors function to add the two vectors.
o Call the subtract_vectors function to subtract the second
vector from the first.
5. Print Results: Print the resulting vectors.

OUTPUT:
EXPERIMENT 6:

AIM: Program to find dot product of two vectors.

REQUIREMENTS:
 Libraries to be used: No external libraries are required for this
experiment as dot product can be done using Python's built-in lists.
 Python version to be used: Python 3.x or above.

Python Code:
def dot_product(vector1, vector2):
# Check if the vectors have the same length
if len(vector1) != len(vector2):
raise ValueError("Vectors must have the same length")

# Initialize result to 0
result = 0

# Calculate the dot product by summing the product of


corresponding elements
for i in range(len(vector1)):
result += vector1[i] * vector2[i]

return result

# Example usage
vector1 = [1, 2, 3]
vector2 = [4, 5, 6]

try:
result = dot_product(vector1, vector2)
print("Dot Product:", result)
except ValueError as e:
print(e)
ALGORITHM:

i. Input Vectors: Take two vectors as input.


ii. Check Length : Ensure both vectors have the
same length. If not, show an error.
iii. Check for Empty Vectors : Ensure neither vector
is empty. If empty, show an error.
iv. Check Numeric Values : Ensure all elements in
both vectors are numbers. If not, show an error.
v. Initialize Result : Set a variable `result` to 0.
vi. Iterate and Multiply : For each index, multiply
corresponding elements of the two vectors and add
to
`result`.
vii. Output Result : Return or print the final `result`, which
is the dot product.

OUTPUT:
PRECAUTIONS:

 Check for Equal Lengths: Ensure vectors have the


same length.
 Check for Empty Vectors: Prevent empty vectors
from causing issues.
 Check for Numeric Values: Ensure all elements in
the vectors are numeric.
 Efficient Calculation: Use a simple loop or
efficient built-in functions to calculate the dot
product.
EXPERIMENT 7:

AIM: Program to find multiply two square matrices


of any order.

REQUIREMENTS:
 Libraries to be used: NumPy library is used for data calculations.
This includes linalg function which contains variety of linear
algebra functions for working with matrix and vectors.
 Python version to be used: Python 3.x or above.

Python Code:
import numpy as np

def multiply_square_matrices(matrix1, matrix2):


matrix1 = np.array(matrix1)
matrix2 = np.array(matrix2)

# Check if both matrices are square


if matrix1.shape[0] != matrix1.shape[1] or
matrix2.shape[0] != matrix2.shape[1]:
return "Error: Both matrices must be square."

# Check if both matrices are of the same size


if matrix1.shape != matrix2.shape:
return "Error: Both matrices must have the same
dimensions."

# Perform matrix multiplication


result = np.dot(matrix1, matrix2)
return result
# Example Input
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix2 = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]

result = multiply_square_matrices(matrix1, matrix2)


# Display the result or error message
if isinstance(result, str):
print(result)
else:
print("Resultant Matrix:")
print(result)

ALGORITHM:
i. Input: Two matrices A and B.
ii. Validate Input:
a. Check if both matrices are square:
i. Ensure rows = columns for A and B.
b. Check if dimensions match:
i. Ensure the size of A equals the size of B.
iii. Matrix Multiplication:
a. If valid, compute C=A⋅B using np.dot.
iv. Output: Return the resultant matrix C if valid otherwise return error.
OUTPUT:

PRECAUTIONS:

1. Square Matrices: Ensure both matrices are square (n×n).


2. Matching Dimensions: Both matrices must have the same size.
3. Numeric Data: Matrices should contain only numeric values.
4. Valid Shape: Confirm matrices are 2D arrays.
5. Error Handling: Check for shape and dimension
compatibility before multiplying.
EXPERIMENT 8:

AIM: Program to find inverse of 3x3 matrix.

REQUIREMENTS:
 Libraries to be used: NumPy library is used for data calculations.
This includes linalg function which contains variety of linear algebra
functions for working with matrix and vectors.
 Python version to be used: Python 3.x or above.

Python Code:
import numpy as np

# Predefined 3x3 matrix


matrix = np.array([[2, 1, 1],
[1, 3, 2],
[1, 0, 0]])
# Check if the determinant is non-zero
det = np.linalg.det(matrix)

if det!= 0:
# Compute the inverse
inverse = np.linalg.inv(matrix)
print("The inverse of the matrix is:”)
print(inverse)

else:
print("The matrix is singular and does not have an
inverse.")
ALGORITHM:
i. Start
ii. Define the matrix:
a. Initialize a predefined 3×3 matrix as a NumPy array.
iii. Calculate the determinant:
a. Use np.linalg.det(matrix) to compute the determinant of
the matrix.
iv. Check if the matrix is invertible:
a. If the determinant is non-zero:
i. Compute the inverse using np.linalg.inv(matrix).
ii. Display the inverse of the matrix.
b. Else, if the determinant is zero:
i. Display a message that the matrix is singular and does
not have an inverse.
v. End

OUTPUT:
PRECAUTIONS:

1. Matrix Shape: Ensure the matrix is 3×33 \times 3 (square).


2. Determinant Check: Verify that the determinant is non-zero
before calculating the inverse.
3. Input Validation: Ensure all matrix elements are numeric
and properly formatted.
4. Avoid Hardcoding: Use dynamic checks like matrix.shape
for flexibility.
5. Variable Safety: Do not overwrite critical variables (e.g., matrix, det).
6. Test Edge Cases: Test with identity, zero, and near-singular matrices.
7. Efficient Libraries: Use trusted tools like NumPy for accuracy
and performance.
EXPERIMENT 9:

AIM: Program to find eigen values of a 3x3 matrix.

REQUIREMENTS:
 Libraries to be used: NumPy library is used for data calculations.
This includes linalg function which contains variety of linear
algebra functions for working with matrix and vectors.
 Python version to be used: Python 3.x or above.

Python Code:

import numpy as np
# Predefined 3x3 matrix
matrix = np.array([[2, 1, 1],
[1, 3, 2],
[1, 0, 0]])

# Calculate the eigenvalues


eigenvalues = np.linalg.eigvals(matrix)

# Output the eigenvalues


print("The eigenvalues of the matrix are:")
print(eigenvalues)
Algorithm:
1. Start
2. Define the matrix:
o Initialize a predefined 3×33 \times 3 matrix as a
NumPy array.
3. Calculate eigenvalues:
o Use np.linalg.eigvals(matrix) to compute the
eigenvalues of the matrix.
4. Output the eigenvalues:
o Display the computed eigenvalues.
5. End

OUTPUT:
PRECAUTIONS:

1. Matrix Shape: Ensure the matrix is 3×33 \times 3 (square).


2. Data Type: Verify all matrix elements are numeric (int
or float).
3. Symmetry: For symmetric matrices, eigenvalues
are guaranteed to be real.
4. Complex Eigenvalues: Be prepared to handle complex
eigenvalues for non-symmetric matrices.
5. Trusted Library: Use reliable tools like NumPy for
accurate calculations.
6. Edge Cases: Test with special matrices like identity
or diagonal matrices for validation.
EXPERIMENT 10:

AIM: Program to solve linear equations containing


3 variables.

REQUIREMENTS:
 Libraries to be used: NumPy library is used for data calculations.
This includes linalg function which contains variety of linear
algebra functions for working with matrix and vectors.
 Python version to be used: Python 3.x or above.

Python Code:
import numpy as np
def solve_linear_equations(coefficients, constants):

# Convert inputs to numpy arrays


A = np.array(coefficients)
B = np.array(constants)

determinant = np.linalg.det(A)
if determinant == 0:
return "The system has no unique solution
(determinant is zero)."

# Solve the system of equations


solution = np.linalg.solve(A, B)
return solution

# Example Input
coefficients = [
[2, -1, 3],
[1, 2, -1],
[3, -2, 4] ]
constants = [5, 6, 8]

# Solve
solution = solve_linear_equations(coefficients,
constants)
print("Solution:", solution)

Algorithm:
i. Input:
a. A 3x3 coefficient matrix AA.
b. A 1x3 constant vector BB.
ii. Check Determinant:
a. Calculate det(A)\text{det}(A) using np.linalg.det(A).
b. If det(A) = 0, return "No unique solution".
iii. Solve the System:
a. If det(A)≠0, calculate X=A−1B or use np.linalg.solve(A, B).
iv. Output:
a. Return the solution vector X.

OUTPUT:
PRECAUTIONS:

1. Determinant Check: Ensure the determinant of the coefficient


matrix is non-zero before solving, as a zero determinant
indicates no unique solution (either infinitely many solutions or
none).
2. Input Validation: Verify the input dimensions:
o The coefficient matrix A must be 3×3.
o The constant vector B must have exactly 3 elements.
3. Numerical Stability: Beware of round-off errors for matrices
with very small determinants, which may lead to inaccurate
solutions. Consider scaling or using higher precision if
needed.

You might also like