Python Computer Scince
Python Computer Scince
This experiment involves using NumPy in Python to create and manipulate matrices. NumPy
is a powerful library for numerical computing that provides functions for matrix operations.
Concepts Covered:
If you haven't installed NumPy, use the following command in your terminal or command
prompt:
import numpy as np
Output:
Matrix A:
[[1 2 3]
[4 5 6]
[7 8 9]]
B = np.arange(1, 10).reshape(3, 3)
print("Matrix B:\n", B)
C = A + B
print("Matrix Addition:\n", C)
D = A - B
print("Matrix Subtraction:\n", D)
3. Transpose of a Matrix
G = A.T
print("Transpose of A:\n", G)
4. Determinant of a Matrix
det_A = np.linalg.det(A)
print("Determinant of A:", det_A)
5. Inverse of a Matrix (if determinant ≠ 0)
if np.linalg.det(A) != 0:
inv_A = np.linalg.inv(A)
print("Inverse of A:\n", inv_A)
else:
print("Matrix A is singular, inverse does not exist.")
The Gauss elimination method is used to solve a system of linear equations by converting
the system into an upper triangular matrix and then performing back-substitution.
Partial pivoting improves numerical stability by swapping rows so that the largest element in
the current column becomes the pivot.
where A is the coefficient matrix, x is the variable vector, and b is the constant matrix.
We will perform row operations to make the system upper triangular and then use back-
substitution.
import numpy as np
# Back Substitution
x = np.zeros(n)
for i in range(n - 1, -1, -1):
x[i] = (Ab[i, -1] - np.sum(Ab[i, i + 1:n] * x[i + 1:n])) /
Ab[i, i]
return x
Example Output
Solution: [ 2. 3. -1.]
This means:
4. Lagrange Interpolation
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import lagrange
# Plot
plt.scatter(x, y, color='red', label='Given Points')
plt.plot(x_new, y_new, label='Lagrange Interpolation')
plt.legend()
plt.grid()
plt.show()
for i in range(n):
L = 1
for j in range(n):
if i != j:
L *= (x - x_values[j]) / (x_values[i] - x_values[j])
result += y_values[i] * L
return result
x_interp = 1.5
y_interp = lagrange_interpolation(x_values, y_values, x_interp)
print(f"Interpolated value at x = {x_interp}: {y_interp}")
1. Using scipy.interpolate.lagrange()
This function generates the Lagrange polynomial automatically.
The polynomial is evaluated at new points for plotting.
The graph visualizes the interpolation.
2. Manual Lagrange Interpolation Function
It calculates each Lagrange basis polynomial manually.
Example Output
Since NumPy does not have a direct function for Lagrange Interpolation like SciPy, we will
implement it manually.
Step 1: Understanding the Method
We will create a function that computes the Lagrange Interpolating Polynomial using NumPy.
import numpy as np
import matplotlib.pyplot as plt
for i in range(n):
L = 1
for j in range(n):
if i != j:
L *= (x_interp - x_values[j]) / (x_values[i] -
x_values[j])
result += y_values[i] * L
return result
# Plot
plt.scatter(x_values, y_values, color='red', label='Given Points')
plt.plot(x_new, y_new, label='Lagrange Interpolation (NumPy)')
plt.legend()
plt.grid()
plt.show()
Example Output
This means that for x=1.5x = 1.5, the estimated y value is 2.375.
Now, we will visualize Lagrange Interpolation using Matplotlib. This experiment focuses on
plotting the Lagrange polynomial while ensuring the points align with the interpolation
function.
Step 1: Understanding the Need for Matplotlib
Matplotlib helps in visualizing how the interpolation curve fits the given data points.
We will manually compute the Lagrange polynomial and plot it using Matplotlib.
We will:
import numpy as np
import matplotlib.pyplot as plt
for i in range(n):
L = 1
for j in range(n):
if i != j:
L *= (x_interp - x_values[j]) / (x_values[i] -
x_values[j])
result += y_values[i] * L
return result
Example Output
The plot will show how the polynomial smoothly connects the given points.
1. Concept
Newton’s forward difference interpolation formula is given by:
Here’s a Python script using NumPy to calculate the forward differences and then evaluate
the polynomial at a given xx:
import numpy as np
def forward_diff_table(y_values):
"""
Constructs the forward difference table.
Returns a list of lists where each list represents a column in the
table.
"""
n = len(y_values)
diff_table = [y_values.copy()]
return diff_table
return result
# Value to interpolate
x_interp = 2.5
Iteratively add terms: each term is the product of the uu factors, the corresponding
forward difference from the table, and divided by the factorial of the term's order.
3. Output:
The code prints the interpolated value for x=2.5
8. Newton Interpolation using Backward Difference
This method is similar to the forward difference method but is used when interpolation is
required near the end of the data set. The backward difference method uses differences
calculated from the end of the table.
1. Concept
import numpy as np
def backward_diff_table(y_values):
"""
Constructs the backward difference table.
Returns a list of arrays where each array represents a column in
the table.
"""
n = len(y_values)
diff_table = [np.array(y_values)]
return diff_table
return result
3. Output:
The script prints the interpolated value at x=3.5
Overview:
The Gauss Elimination method is a systematic approach for solving a system of linear
equations by transforming the coefficient matrix into an upper triangular form and then using
back substitution to find the solution.
AX= B
where:
2. Example Problem
3. Python Implementation
import numpy as np
# Back Substitution
X = np.zeros(n)
for i in range(n - 1, -1, -1):
X[i] = (B[i] - np.dot(A[i, i + 1:], X[i + 1:])) / A[i][i]
return X
1. Forward Elimination:
Convert the matrix into an upper triangular form by making elements below the main
diagonal zero.
2. Back Substitution:
Start from the last equation and solve for variables one by one.
3. Output:
The solution to the system of equations is printed as an array.
This experiment expands on the previous Gauss Elimination method, but now we will:
1. Forward Elimination:
Convert the given system into an upper triangular matrix by eliminating the lower
elements.
2. Back Substitution:
Solve the upper triangular system starting from the last row and moving upwards.
3. Function Calls:
Use separate functions for forward elimination, back substitution, and main
function to solve the system.
2. Python Implementation
import numpy as np
1. Function forward_elimination(A, B)
Converts the system into upper triangular form by eliminating lower elements.
Uses row operations to make elements below the main diagonal zero.
2. Function back_substitution(A, B)
Solves for unknowns starting from the last row using back substitution.
3. Function gauss_elimination(A, B)
Calls forward_elimination() and back_substitution() to solve the system.
4. Example Input:
Solves a system of 3 equations with 3 variables.
5. Output:
The solution is printed as an array.
1. Overview
Ax=B
where:
3. Python Implementation
import numpy as np
for i in range(n):
sum1 = sum(A[i][j] * x_new[j] for j in range(i)) # Using
updated values
sum2 = sum(A[i][j] * x[j] for j in range(i + 1, n)) #
Using old values
x_new[i] = (B[i] - sum1 - sum2) / A[i][i]
# Check for convergence
if np.linalg.norm(x_new - x, ord=np.inf) < tol:
print(f"Converged in {iteration+1} iterations.")
return x_new
Converged in 7 iterations.
Solution: [0.5 1. 0.5]
1. Overview
The Newton-Raphson method is an iterative numerical technique used to find the roots of a
nonlinear equation of the form:
f(x)= 0
This method is fast and efficient, especially when the initial guess is close to the actual root.
2. Newton-Raphson Formula
where:
3. Python Implementation
import numpy as np
if dfx == 0:
print("Derivative is zero. Method fails.")
return None
x = x_new
# Initial guess
x0 = 2
Converged in 5 iterations.
Root of the equation: 2.7065
1. Overview
Numerical integration is used when an integral cannot be solved analytically. Two common
methods for approximating definite integrals are:
import numpy as np
def f(x):
""" Function to integrate: Example f(x) = x^2 """
return x**2
trapezoidal_result = trapezoidal_rule(a, b, n)
simpsons_result = simpsons_rule(a, b, n)
1. Overview
Curve fitting is used to find the best-fitting curve for a given set of data points. The Least
Squares Method is a popular approach that minimizes the sum of squared errors between
the observed data and the fitted function.
Data analysis
Machine learning
Engineering applications
3. Python Implementation
import numpy as np
import matplotlib.pyplot as plt
# Display results
print(f"Slope (m): {m:.2f}")
print(f"Intercept (c): {c:.2f}")
1. Overview
import numpy as np
import matplotlib.pyplot as plt
# Initial conditions
x0, y0 = 0, 1 # y(0) = 1
h = 0.1 # Step size
xn = 1 # Solve from x=0 to x=1
# Plot results
plt.plot(x_vals, y_vals, marker='o', label="Euler Approximation")
plt.xlabel("x")
plt.ylabel("y")
plt.title("Euler’s Method Approximation")
plt.legend()
plt.show()
# Display results
print("x values:", x_vals)
print("y values:", y_vals)
The Runge-Kutta methods are a group of iterative techniques used to solve ordinary
differential equations (ODEs) more accurately than Euler’s method. The most common
version is the 4th-order Runge-Kutta (RK4) method, which is popular due to its good
balance between accuracy and computational effort.
For an ODE:
2. Python Implementation
import numpy as np
import matplotlib.pyplot as plt
Returns:
x_values, y_values : arrays of computed x and y values
"""
x_values = np.arange(x0, xn + h, h)
y_values = np.zeros(len(x_values))
y_values[0] = y0
k1 = h * f(x_n, y_n)
k2 = h * f(x_n + h/2, y_n + k1/2)
k3 = h * f(x_n + h/2, y_n + k2/2)
k4 = h * f(x_n + h, y_n + k3)