Python Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

B.

SC
-I
MAT
HEM
ATIC
SI-
LAB
Index
SI. No. Program Name
Lab 1: Python Basic operations

Lab 2: Computation with Matrices

2.1 Python Program for Matrix Addition


2.2 Python Program for Matrix Subtraction
2.3 Python Program for Matrix Multiplication

2.4 Python Program for Transpose of a Matrix

Lab 3: Python Program for finding Determinant of a Matrix

Lab 4: Python Program for finding Inverse of a Matrix

Lab 5: Python Program for Row reduced Echelon Form

Lab 6: Python Program for finding Rank of a Matrix

Lab 7: Python Program for finding solution of a matrix by Cramer’s rule

Lab 8: Python Program for finding solution of a matrix by Matrix Method

Lab 9: Python Program for Establishing Consistency and solving system of linear equations.

Lab 10: Python Program for Calculating partial derivatives


INTRODUCTION TO PYTHON PROGRAMMING
 Python is a high-level, general-purpose, interpreted, interactive and object-oriented
programming language.
 It was created by Guido van Rossum during 1985- 1990.
 Like Perl, Python source code is also available under the GNU General Public License
(GPL).

Why the name python?

Guido van Rossum was interested on watching a comedy show, which is telecasting on
the BBC channel from 1969 to 1974 The complete Monty Python's Flying Circus.
Guido Van Rossum thought he needed a name that was short, unique, and slightly mysterious for
his programming language, so he decided to call the language Python.
Applications of Python Programming
 Web Development
 Game Development
 Scientific and Numeric applications
 Artificial Intelligence and Machine Learning based applications
 Data Science related applications
 Desktop GUI applications
 Software Development
 Enterprise-level/Business Applications
 Education programs and training courses
 Web Scraping Applications
 Image Processing

Features of Python programming

 Simple and Easy to Learn


 Freeware and Open Source
 Dynamically typed
 Object Oriented Programming and Procedure Oriented Programming
 Extensive Library
 Embedded
 Extensible
 Interpreted
 Portability
 Platform Independent
Lab 1: Python Basic operations
Example:
name = input("What's your name? ")
print("Nice to meet you " + name + "!")

Output:
What's your name? "Alex"
Nice to meet you Alex!

name = input("What's your name? ")


print("Nice to meet you " + name + "!")

 The If statement and the If - Else statement


 Decision making is the most important aspect of almost all the programming
languages. As the name implies, decision making allows us to run a particular block
of code for a particular decision. Here, the decisions are made on the validity of the
particular conditions. Condition checking is the backbone of decision making. The if
statement is used to test a particular condition and if the condition is true, it executes
a block of code known as if-block. The condition of the if statement can be any valid
logical expression which can be either evaluated to true or false.

 The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition. If the condition is true, then the if-block
is executed. Otherwise, the else-block is executed.
1. Python program to check whether a person is eligible for vote.
n=int(input("Enter age: "))
if(n >= 18):
print("Eligible for vote")

2. Python program to check whether the given number is even or odd.

n = int(input())
if(n%2 = = 0):
print(“Number is an even number‟)
else:
print(" Number is an odd number ")

Output:
20
Number is an even number

n = int(input())
if(n%2 = = 0):
print("Number is an even number")
else:
print("Number is an odd number")

3. Python program to check whether the year is leap year or not

n = int(input((“Enter a number”))
if(n%4==0):
print(“Leap year”)
else:
print(“Not Leap year”)
Output:
2000
Leap year

n = int(input("Enter a number"))
if(n%4==0):
print("Leap year")
else:
print("Not Leap year")

4. Write python program to read a particular student mark and print the grade

n = int(input("enter the number: "))


if (n < 25):
print("Fail")
elif (n > = 25 and n < 45):
print("pass class")
elif (n > = 45 and n < 50):
print("second class")
elif (n > = 50 and n < 80):
print("First class")
else:
print("Distinction")

Output:
39
pass class

n = int(input("enter the number: "))


if (n < 25):
print("Fail")
elif (n > = 25 and n < 45):
print("pass class")
elif (n > = 45 and n < 50):
print("second class")
elif (n > = 50 and n < 80):
print("First class")
else:
print("Distinction")

The range() function:


The range() function is used to generate the sequence of the numbers. If we pass the
range(10), it will generate the numbers from 0 to 9. The syntax of the range() function is given
below.
Syntax:
range(start, stop, step size)
The start represents the beginning of the iteration.
The stop represents that the loop will iterate till stop-1. The range(1,5) will generate
numbers 1 to 4 iterations. It is optional.
The step size is used to skip the specific numbers from the iteration. It is optional to use. By
default, the step size is 1. It is optional.
1. Program to print the sum of first n natural numbers
n = int(input(“Enter value: ”))
sum = 0
for val in range(1, n+1):
sum + = val
print(“The sum is”, sum)

Output:
Enter range: 5
The sum is 15

n = int(input("Enter value: ")) # Taking input from the user

sum = 0
for val in range(1, n + 1): # Using n + 1 to include the input value in the
sum += val
print("The sum is", sum) # Printing the sum in each iteration
2. Python program to find the factorial of a given number.

n = int(input("enter the number: "))


factorial = 1
if (n<0):
print("factorial not exist")
elif (n==0):
print("0!=1")
else:
for i in range(1, n+1):
factorial=factorial*i
print("the factorial of", n, "is", factorial)

Output:
Enter a number:7
The factorial of 7 is 5040

n = int(input("enter the number: "))


factorial = 1
if (n<0):
print("factorial not exist")
elif (n==0):
print("0!=1")
else:
for i in range(1, n+1):
factorial=factorial*i
print("the factorial of", n, "is", factorial)
3. Python program for basic matrix entries.

A=[[1,4,5,12], [5,7,8,9], [10,3,0,5]]


print("A=",A)
print("A[0]=",A[0]) #1st row
print("A[1][3]",A[1][3]) #2row 4th element
print("A[0][2]",A[0][2]) #1st row 3rd element
column=[];
for row in A:
column.append(row[1])
print("2nd column=", column)

output:
A = [1,4,5,12]
[5,7,8,9]
[10,3,0,5]

A[0] = [1,4,5,12]
A[1][3] = 9
A[0][2] = 5
2nd column= [4, 7, 3]

A=[[1,4,5,12], [5,7,8,9], [10,3,0,5]]


print("A=",A)
print("A[0]=",A[0]) #1st row
print("A[1][3]",A[1][3]) #2row 4th element
print("A[0][2]",A[0][2]) #1st row 3rd element
column=[];
for row in A:
column.append(row[1])
print("2nd column=", column)
Lab 2: Computation with Matrices
2.1 Python Program for Matrix Addition

import numpy as np

# Function to add two matrices


def add_matrices(matrix1, matrix2):
result_matrix = np.add(matrix1, matrix2)
return result_matrix

# Input matrix dimensions


rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))

# Input elements for matrix1


print("Enter elements for matrix1:")
matrix1 = []
for i in range(rows):
row = []
for j in range(columns):
element = int(input(f"Enter element at position ({i+1}, {j+1}): "))
row.append(element)
matrix1.append(row)

# Input elements for matrix2


print("Enter elements for matrix2:")
matrix2 = []
for i in range(rows):
row = []
for j in range(columns):
element = int(input(f"Enter element at position ({i+1}, {j+1}): "))
row.append(element)
matrix2.append(row)

# Call the function to add the matrices


result_matrix = add_matrices(np.array(matrix1), np.array(matrix2))

# Print the result matrix


print("Result Matrix:")
print(result_matrix)
import numpy as np

# Function to add two matrices


def add_matrices(matrix1, matrix2):
result_matrix = np.add(matrix1, matrix2)
return result_matrix

# Input matrix dimensions


rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))

# Input elements for matrix1


print("Enter elements for matrix1:")
matrix1 = []
for i in range(rows):
row = []
for j in range(columns):
element = int(input(f"Enter element at position ({i+1}, {j+1}): "))
row.append(element)
matrix1.append(row)

# Input elements for matrix2


print("Enter elements for matrix2:")
matrix2 = []
for i in range(rows):
row = []
for j in range(columns):
element = int(input(f"Enter element at position ({i+1}, {j+1}): "))
row.append(element)
matrix2.append(row)

# Call the function to add the matrices


result_matrix = add_matrices(np.array(matrix1), np.array(matrix2))

# Print the result matrix


print("Result Matrix:")
print(result_matrix)
2.1 Python Program for Matrix Addition

import numpy as np

# Example matrix addition


M1 = np.array([[1, -2, 3],
[4, 5, -6],
[-7, -8, 9]])

M2 = np.array([[9, 0, 7],
[0, 5, 4],
[3, 2, 1]])

# Add the matrices using numpy.add()


result_matrix = np.add(M1, M2)

# Print the result matrix


print(result_matrix)

2.2 Python Program for Matrix Subtraction

import numpy as np
# Example matrix addition
M1 = np.array([[1, -2, 3], [4, 5, -6], [-7, -8, 9]])
M2 = np.array([[9, 0, 7], [0, 5, 4], [3, 2, 1]])
#Subtract the matrices using numpy.subtract()
result_matrix = np.subtract(M1, M2)

# Print the result matrix


print(result_matrix)
2.3 Python Program for Matrix Multiplication
Get Matrix Dimensions from User:

rows1, cols1, rows2, and cols2 are obtained from the user as the number of rows and columns for
the two matrices.

Check Validity for Matrix Multiplication:

if cols1 != rows2: checks if the number of columns in the first matrix is equal to the number of
rows in the second matrix. If not, it prints an error message and exits because matrices with these
dimensions cannot be multiplied together.

Create Matrices based on User Input:

matrix1 and matrix2 are initialized as empty matrices.

User input is taken for each element of matrix1 and matrix2 using nested loops.

For each matrix, it prompts the user to input elements row-wise.

Perform Matrix Multiplication:

result is initialized as a matrix filled with zeros, having dimensions rows1 x cols2.

Three nested loops are used to perform matrix multiplication.

The outermost loops iterate through the rows of matrix1 (rows1) and the columns of matrix2
(cols2).

The innermost loop (k) iterates through the columns of matrix1 and the rows of matrix2,
multiplying corresponding elements and summing them up to calculate the elements of the
resulting matrix result.

Print the Result Matrix:

After performing multiplication, the code prints the resulting matrix (result) to display the
outcome of the matrix multiplication.

This code essentially performs matrix multiplication for matrices entered by the user, provided
that the dimensions satisfy the requirements for matrix multiplication (where the number of
columns in the first matrix must match the number of rows in the second matrix).
#Get the dimensions of the matrices from the user
rows1 = int(input("Enter the number of rows for matrix 1: "))
cols1 = int(input("Enter the number of columns for matrix 1: "))
rows2 = int(input("Enter the number of rows for matrix 2: "))
cols2 = int(input("Enter the number of columns for matrix 2: "))

# Check if the matrices can be multiplied


if cols1 != rows2:
print("Error: The number of columns in matrix 1 must match the number of rows in matrix 2.")
exit()

# Create the matrices based on user input


matrix1 = []
matrix2 = []
print("Enter the elements of matrix 1:")

# Get input for matrix 1


for i in range(rows1):
row = []
for j in range(cols1):
element = int(input("Enter element at position ({}, {}): ".format(i+1, j+1)))
row.append(element)
matrix1.append(row)

print("Enter the elements of matrix 2:")


# Get input for matrix 2
for i in range(rows2):
row = []
for j in range(cols2):
element = int(input("Enter element at position ({}, {}): ".format(i+1, j+1)))
row.append(element)
matrix2.append(row)

# Perform matrix multiplication


result = [[0] * cols2 for _ in range(rows1)]

for i in range(rows1):
for j in range(cols2):
for k in range(cols1):
result[i][j] += matrix1[i][k] * matrix2[k][j]

# Print the result matrix


print("Result Matrix:")
for row in result:
print(row)

OR
 Using NumPy library,

# Perform matrix multiplication

import numpy as np

# Define the matrices


matrix1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

matrix2 = np.array([[10, 11, 12],


[13, 14, 15],
[16, 17, 18]])

# Perform matrix multiplication


result = np.dot(matrix1, matrix2)

# Print the result matrix


print("Result Matrix:", result)
# Perform matrix multiplication

import numpy as np

# Define the matrices


matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

matrix2 = np.array([[10, 11, 12], [13, 14, 15], [16, 17, 18]])

# Perform matrix multiplication


result = np.dot(matrix1, matrix2)

# Print the result matrix


print("Result Matrix:", result)

2.4 Python Program for Transpose of a Matrix

 def transpose_matrix(matrix):: This line defines a function called transpose_matrix that


takes a matrix as input.
 rows = len(matrix) and cols = len(matrix[1]): These lines calculate the number of rows
and columns in the input matrix. len(matrix) gives the number of rows, and
len(matrix[1]) (assuming all rows have the same number of elements) gives the number
of columns by looking at the length of the first row.
 transpose = [[1 for _ in range(rows)] for _ in range(cols)]: This line initializes a new
matrix called transpose with swapped dimensions (number of rows becomes number of
columns and vice versa). It uses list comprehension to create a matrix filled with 1s,
having the dimensions of cols x rows.
 for i in range(rows): and for j in range(cols):: These nested loops iterate through the
original matrix's elements, using i for rows and j for columns.
 transpose[j][i] = matrix[i][j]: This line assigns the value of matrix[i][j] to transpose[j][i],
effectively transposing the matrix by swapping rows with columns.
 return transpose: This statement returns the transposed matrix.
 The subsequent lines of code prompt the user to input the number of rows and columns,
create an empty matrix, and fill it with user-provided values. Then, it calls the
transpose_matrix() function to find the transpose of the matrix.
The code is a basic implementation to find the transpose of a matrix in Python. It takes user input
for the matrix size and elements and then computes and displays the transpose of the entered
matrix

def transpose_matrix(matrix):
# Get the number of rows and columns in the matrix
rows = len(matrix)
cols = len(matrix[1])

# Create a new matrix with swapped dimensions


transpose = [[1 for _ in range(rows)] for _ in range(cols)]

# Fill the transpose matrix with the elements from the original matrix
for i in range(rows):
for j in range(cols):
transpose[j][i] = matrix[i][j]
return transpose

# Get the number of rows and columns from the user


rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))

# Create an empty matrix


matrix = []

# Get the matrix elements from the user


print("Enter the matrix elements:")

for i in range(rows):
row = []
for j in range(cols):
element = int(input(f"Enter element [{i+1}][{j+1}]: "))
row.append(element)
matrix.append(row)

# Find the transpose of the matrix


transpose = transpose_matrix(matrix)

# Print the original matrix


print("Original Matrix:")
for row in matrix:
print(row)

# Print the transpose matrix


print("\nTranspose Matrix:")
for row in transpose:
print(row)

def transpose_matrix(matrix):
# Get the number of rows and columns in the matrix
rows = len(matrix)
cols = len(matrix[1])

# Create a new matrix with swapped dimensions


transpose = [[1 for _ in range(rows)] for _ in range(cols)]

# Fill the transpose matrix with the elements from the original matrix
for i in range(rows):
for j in range(cols):
transpose[j][i] = matrix[i][j]
return transpose

# Get the number of rows and columns from the user


rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))

# Create an empty matrix


matrix = []

# Get the matrix elements from the user


print("Enter the matrix elements:")

for i in range(rows):
row = []
for j in range(cols):
element = int(input(f"Enter element [{i+1}][{j+1}]: "))
row.append(element)
matrix.append(row)

# Find the transpose of the matrix


transpose = transpose_matrix(matrix)

# Print the original matrix


print("Original Matrix:")
for row in matrix:
print(row)

# Print the transpose matrix


print("\nTranspose Matrix:")
for row in transpose:
print(row)

OR
 Using NumPy library,

# Find the transpose of the matrix

import numpy as np

# Create a matrix
matrix = np.array([[1, 2, 3], [0, 11, 6], [-6, 8, 10]])

# Find the transpose of the matrix


transpose = np.transpose(matrix)

# Print the original matrix


print("Original Matrix:")
print(matrix)

# Print the transpose matrix


print("\nTranspose Matrix:")
print(transpose)

# Find the transpose of the matrix

import numpy as np

# Create a matrix
matrix = np.array([[1, 2, 3], [0, 11, 6], [-6, 8, 10]])

# Find the transpose of the matrix


transpose = np.transpose(matrix)

# Print the original matrix


print("Original Matrix:")
print(matrix)

# Print the transpose matrix


print("\nTranspose Matrix:")
print(transpose)
Lab 3: Python Program for finding Determinant of a Matrix
 Importing the NumPy Package:
import numpy as np: This imports the NumPy library and assigns it the alias np, which allows
access to NumPy functions using the prefix np.
 Creating a Square NumPy Matrix:
arr = np.array([[-1, 3, 0], [2, 1, -5], [1, 4, -2]]): This line creates a 3x3 NumPy array (a matrix)
with specified elements.
 Displaying the Matrix:
print("Matrix ="): This prints a message to indicate the display of the matrix.
print(arr): This displays the contents of the NumPy matrix arr created earlier.
 Calculating the Determinant of the Matrix:
determinant = np.linalg.det(arr): This line calculates the determinant of the matrix arr using
NumPy's np.linalg.det() function and stores the result in the variable determinant.
 Rounding and Printing the Determinant:
print(round(determinant)): This prints the determinant after rounding it to the nearest integer
using the round() function. The determinant value is displayed as an integer.

# importing Numpy package


import numpy as np

# Creating a nXn numpy matrix


arr = np.array([[-1, 3, 0], [2, 1, -5], [1, 4, -2]])

# Displaying the Matrix


print("Matrix =")
print(arr)

# Calculating the determinant of matrix


determinant = np.linalg.det(arr)

print(round(determinant))
# importing Numpy package
import numpy as np

# Creating a nXn numpy matrix


arr = np.array([[-1, 3, 0], [2, 1, -5], [1, 4, -2]])

# Displaying the Matrix


print("Matrix =")
print(arr)

# Calculating the determinant of matrix


determinant = np.linalg.det(arr)

print(round(determinant))

Lab 4: Python Program for finding Inverse of a Matrix


 Importing the NumPy Package:

import numpy as np: Imports the NumPy library with the alias np, which allows access to
NumPy functions using np.

 Creating a Square NumPy Matrix:

arr = np.array([[2, 0, 1], [-2, 3, 4], [-5, 5, 6]]): Creates a 3x3 NumPy array (a matrix) named arr
with specified elements.

 Displaying the Matrix:

print("Matrix ="): Prints a message to indicate the display of the matrix.

print(arr): Displays the contents of the NumPy matrix arr created earlier.

 Calculating the Inverse of the Matrix:

inverse = np.linalg.inv(arr): Computes the inverse of the matrix arr using NumPy's
np.linalg.inv() function and stores the result in the variable inverse.

 Displaying the Inverse Matrix:

print(inverse): Prints the calculated inverse of the matrix arr.


# importing Numpy package
import numpy as np

# Creating a nXn numpy matrix


arr = np.array([[2, 0, 1], [-2, 3, 4], [-5, 5, 6]])

# Displaying the Matrix


print("Matrix =")
print(arr)

# Calculating the inverse of matrix


inverse = np.linalg.inv(arr)
print(inverse)

# importing Numpy package


import numpy as np

# Creating a nXn numpy matrix


arr = np.array([[2, 0, 1], [-2, 3, 4], [-5, 5, 6]])

# Displaying the Matrix


print("Matrix =")
print(arr)

# Calculating the inverse of matrix


inverse = np.linalg.inv(arr)
print(inverse)
Lab 5: Python Program for Row reduced Echelon Form
 Importing SymPy:

from sympy import *: Imports the SymPy library, enabling the use of its functions without
prefixing them with sympy.

 Creating a Matrix:

M = Matrix([[2,3,-1,-1],[1,-1,-2,-4],[3,1,3,-2],[6,3,0,-7]]): Creates a 4x4 matrix M using


SymPy's Matrix() function, initialized with the provided elements.

 Displaying the Original Matrix:

print("Matrix : {} ".format(M)): Prints the original matrix M.

 Reduced Row Echelon Form (RREF) Calculation:

M_rref = M.rref(): Computes the Reduced Row Echelon Form (RREF) of the matrix M using the
rref() method from SymPy. The RREF is stored in the variable M_rref.

 Displaying the RREF and Pivot Columns:

print("The Row echelon form of matrix M and the pivot columns : {}".format(M_rref)): Prints
the RREF of matrix M along with the pivot columns.

# import sympy
from sympy import *

M = Matrix([[2,3,-1,-1],[1,-1,-2,-4],[3,1,3,-2],[6,3,0,-7]])
print("Matrix : {} ".format(M))

# Use sympy.rref() method


M_rref = M.rref()

print("The Row echelon form of matrix M and the pivot columns : {}".format(M_rref))

# import sympy
from sympy import *
M = Matrix([[2,3,-1,-1],[1,-1,-2,-4],[3,1,3,-2],[6,3,0,-7]])
print("Matrix : {} ".format(M))

# Use sympy.rref() method


M_rref = M.rref()

print("The Row echelon form of matrix M and the pivot columns :


{}".format(M_rref))

Lab 6: Python Program for finding Rank of a Matrix


 Importing the NumPy Package:

import numpy as np: Imports the NumPy library and assigns it the alias np, allowing access to
NumPy functions using the prefix np.

 Creating a NumPy Matrix:

arr = np.array([[0, 2, 3, 4], [2, 3, 5, 4], [4, 8, 13, 12]]): Creates a 3x4 NumPy array (a matrix)
named arr with specified elements.

 Displaying the Matrix:

print("Matrix ="): Prints a message to indicate the display of the matrix.

print(arr): Displays the contents of the NumPy matrix arr created earlier.

 Calculating the Rank of the Matrix:

rank = np.linalg.matrix_rank(arr): Calculates the rank of the matrix arr using NumPy's
np.linalg.matrix_rank() function and stores the result in the variable rank.

 Printing the Rank:


# importing Numpy package
import numpy as np print(rank): Prints the
calculated rank of the matrix
arr.
# Creating a nXn numpy matrix
arr = np.array([[0, 2, 3, 4], [2, 3, 5, 4], [4, 8, 13, 12]])

# Displaying the Matrix


print("Matrix =")
print(arr)

# Calculating the rank of matrix


rank = np.linalg.matrix_rank(arr)
print(rank)
# importing Numpy package
import numpy as np

# Creating a nXn numpy matrix


arr = np.array([[0, 2, 3, 4], [2, 3, 5, 4], [4, 8, 13, 12]])

# Displaying the Matrix


print("Matrix =")
print(arr)

# Calculating the rank of matrix


rank = np.linalg.matrix_rank(arr)
print(rank)

Lab 7: Python Program for finding solution of a matrix by Cramer’s rule


 Importing the NumPy Package:

import numpy as np: Imports the NumPy library and assigns it the alias np, allowing access to
NumPy functions using the prefix np.

 Creating a NumPy Matrix:

arr = np.array([[0, 2, 3, 4], [2, 3, 5, 4], [4, 8, 13, 12]]): Creates a 3x4 NumPy array (a matrix)
named arr with specified elements.

 Displaying the Matrix:

print("Matrix ="): Prints a message to indicate the display of the matrix.

print(arr): Displays the contents of the NumPy matrix arr created earlier.

 Calculating the Rank of the Matrix:

rank = np.linalg.matrix_rank(arr): Calculates the rank of the matrix arr using NumPy's
np.linalg.matrix_rank() function and stores the result in the variable rank.

 Printing the Rank:

print(rank): Prints the calculated rank of the matrix arr.

import numpy as np

def cramer_rule(matrix_A, matrix_B):


det_A = np.linalg.det(matrix_A)
if det_A == 0:
return "Determinant of matrix A is zero. Cramer's rule cannot be applied."

x_matrix = matrix_A.copy()
y_matrix = matrix_A.copy()
z_matrix = matrix_A.copy()

x_matrix[:, 0] = matrix_B
y_matrix[:, 1] = matrix_B
z_matrix[:, 2] = matrix_B

det_x = np.linalg.det(x_matrix)
det_y = np.linalg.det(y_matrix)
det_z = np.linalg.det(z_matrix)
x = det_x / det_A
y = det_y / det_A
z = det_z / det_A

return x, y, z

# Example matrix A and matrix B


matrix_A = np.array([[2, 1, -1],
[1, 1, 1],
[1, -2, -3]])

matrix_B = np.array([3, 1, 4])

solution = cramer_rule(matrix_A, matrix_B)


print("Solution using Cramer's rule:", solution)

import numpy as np

def cramer_rule(matrix_A, matrix_B):


det_A = np.linalg.det(matrix_A)

if det_A == 0:
return "Determinant of matrix A is zero. Cramer's rule cannot be
applied."

x_matrix = matrix_A.copy()
y_matrix = matrix_A.copy()
z_matrix = matrix_A.copy()

x_matrix[:, 0] = matrix_B
y_matrix[:, 1] = matrix_B
z_matrix[:, 2] = matrix_B

det_x = np.linalg.det(x_matrix)
det_y = np.linalg.det(y_matrix)
det_z = np.linalg.det(z_matrix)
x = det_x / det_A
y = det_y / det_A
z = det_z / det_A

return x, y, z

# Example matrix A and matrix B


matrix_A = np.array([[2, 1, -1],
[1, 1, 1],
[1, -2, -3]])

matrix_B = np.array([3, 1, 4])

solution = cramer_rule(matrix_A, matrix_B)


print("Solution using Cramer's rule:", solution)

Lab 8: Python Program for finding solution of a matrix by Matrix


Method
 Importing the NumPy Package:
import numpy as np: Imports the NumPy library and assigns it the alias np, allowing access to
NumPy functions using the prefix np.
 Creating a NumPy Matrix:
arr = np.array([[0, 2, 3, 4], [2, 3, 5, 4], [4, 8, 13, 12]]): Creates a 3x4 NumPy array (a matrix)
named arr with specified elements.
 Displaying the Matrix:
print("Matrix ="): Prints a message to indicate the display of the matrix.
print(arr): Displays the contents of the NumPy matrix arr created earlier.
 Calculating the Rank of the Matrix:
rank = np.linalg.matrix_rank(arr): Calculates the rank of the matrix arr using NumPy's
np.linalg.matrix_rank() function and stores the result in the variable rank.
 Printing the Rank:
print(rank): Prints the calculated rank of the matrix arr.
import numpy as np
# Coefficient matrix (A)
A = np.array([[2, 1, -1], [-3, -1, 2], [-2, 1, 2]])

# Constant matrix (B)


B = np.array([8, -11, -3])

# Solve AX = B for X
X = np.linalg.solve(A, B)

print("Solution for x, y, z:")


print("x =", X[0])
print("y =", X[1])
print("z =", X[2])

import numpy as np

# Coefficient matrix (A)


A = np.array([[2, 1, -1], [-3, -1, 2], [-2, 1, 2]])

# Constant matrix (B)


B = np.array([8, -11, -3])

# Solve AX = B for X
X = np.linalg.solve(A, B)

print("Solution for x, y, z:")


print("x =", X[0])
print("y =", X[1])
print("z =", X[2])
Lab 9: Python Program for Establishing Consistency and solving system
of linear equations.
 Importing NumPy:

import numpy as np: Imports the NumPy library with the alias np to access NumPy functions.

 Coefficient Matrix (A) and Constant Matrix (B):


A = np.array([[1, -4, 7], [3, 8, -2], [7, -8, 26]]): Creates a 3x3 NumPy array representing the
coefficient matrix 'A' of a system of linear equations.

B = np.array([14, 13, 5]): Creates a 1-dimensional NumPy array representing the constant matrix
'B' of the system of linear equations.

 Creating the Augmented Matrix:

augmented_matrix = np.column_stack((A, B.reshape(-1, 1))): Creates an augmented matrix by


combining the coefficient matrix 'A' and the constant matrix 'B'. It stacks 'B' as a new column
next to 'A' using np.column_stack().

 Calculating Ranks:

rank_A = np.linalg.matrix_rank(A): Computes the rank of the coefficient matrix 'A' using
NumPy's np.linalg.matrix_rank() function.

rank_augmented = np.linalg.matrix_rank(augmented_matrix): Calculates the rank of the


augmented matrix.

 Analyzing the System of Equations:

Compares the ranks and shapes of the matrices to determine the nature of the system of equations
(consistent or inconsistent).

If the ranks of the coefficient matrix 'A' and the augmented matrix are equal and equal to the
number of variables, it's a consistent system with a unique solution.

If the ranks are equal but less than the number of variables, it's consistent with infinitely many
solutions.

If the ranks are unequal, it's an inconsistent system with no solution.

 Printing Solutions (if unique solution exists):

If the system is consistent and has a unique solution, it calculates and prints the values of 'x', 'y',
and 'z' using np.linalg.solve() and displays the solution.
import numpy as np

# Coefficient matrix (A)


A = np.array([[1, -4, 7], [3, 8, -2], [7, -8, 26]])

# Constant matrix (B)


B = np.array([14, 13, 5])

# Augmented matrix (combine A and B)


augmented_matrix = np.column_stack((A, B.reshape(-1, 1)))

# Check if the rank of the coefficient matrix equals the rank of the augmented matrix
rank_A = np.linalg.matrix_rank(A)
rank_augmented = np.linalg.matrix_rank(augmented_matrix)

if rank_A == rank_augmented and rank_A == A.shape[1]:


print("The system of equations is consistent and has a unique solution.")
elif rank_A == rank_augmented and rank_A < A.shape[1]:
print("The system of equations is consistent but has infinitely many solutions.")
else:
print("The system of equations is inconsistent and has no solution.")

if rank_A == rank_augmented and rank_A == A.shape[1]:


solution = np.linalg.solve(A, B)
print("Solution for x, y, z:")
print("x =", solution[0])
print("y =", solution[1])
print("z =", solution[2])
import numpy as np

# Coefficient matrix (A)


A = np.array([[1, -4, 7], [3, 8, -2], [7, -8, 26]])

# Constant matrix (B)


B = np.array([14, 13, 5])

# Augmented matrix (combine A and B)


augmented_matrix = np.column_stack((A, B.reshape(-1, 1)))

# Check if the rank of the coefficient matrix equals the rank of the augmented
matrix
rank_A = np.linalg.matrix_rank(A)
rank_augmented = np.linalg.matrix_rank(augmented_matrix)

if rank_A == rank_augmented and rank_A == A.shape[1]:


print("The system of equations is consistent and has a unique solution.")
elif rank_A == rank_augmented and rank_A < A.shape[1]:
print("The system of equations is consistent but has infinitely many
solutions.")
else:
print("The system of equations is inconsistent and has no solution.")

if rank_A == rank_augmented and rank_A == A.shape[1]:


solution = np.linalg.solve(A, B)
print("Solution for x, y, z:")
print("x =", solution[0])
print("y =", solution[1])
print("z =", solution[2])
Lab 10: Python Program for calculating partial derivatives
 Importing SymPy:

import sympy as sp: Imports the SymPy library with the alias sp, providing access to its
functionalities.

 Defining Symbols for Variables:

x, y = sp.symbols('x y'): Defines symbolic variables 'x' and 'y' using sp.symbols(). These symbols
are used to represent variables in mathematical expressions.

 Defining a Multivariable Function:

f = x**2 + y**3 - 2*x*y + 1: Defines a multivariable function 'f' using the previously defined
symbols 'x' and 'y'.

 Calculating Partial Derivatives:

partial_x = sp.diff(f, x): Calculates the partial derivative of function 'f' with respect to 'x' using
sp.diff().

partial_y = sp.diff(f, y): Calculates the partial derivative of function 'f' with respect to 'y' using
sp.diff().

 Printing Partial Derivatives:

print("Partial derivative of f with respect to x =", partial_x): Prints the computed partial
derivative of 'f' with respect to 'x'.

print("Partial derivative of f with respect to y =", partial_y): Prints the computed partial
derivative of 'f' with respect to 'y'.
import sympy as sp

# Define multiple variables


x, y = sp.symbols('x y')

# Define a multivariable function


f = x**2 + y**3 - 2*x*y + 1

# Calculate partial derivatives


partial_x = sp.diff(f, x)
partial_y = sp.diff(f, y)

print("Partial derivative of f with respect to x =", partial_x)


print("Partial derivative of f with respect to y =", partial_y)

import sympy as sp

# Define multiple variables


x, y = sp.symbols('x y')

# Define a multivariable function


f = x**2 + y**3 - 2*x*y + 1

# Calculate partial derivatives


partial_x = sp.diff(f, x)
partial_y = sp.diff(f, y)

print("Partial derivative of f with respect to x =", partial_x)


print("Partial derivative of f with respect to y =", partial_y)

You might also like