Merged Document
Merged Document
ASSIGNMENT REPORT on
BACHELOR OF ENGINEERING
in
at
Step 4: Check if the difference between 𝑥𝑛 and 𝑥𝑛+1 is less than ∈. If true,
declare 𝑥𝑛+1 as the root and stop .Or if iteration count is greater that
number of iteration, if true stop. Else continue update 𝑥𝑛=𝑥𝑛+1 and
continue the iteration process from step 2.
Flowchart:
Reference Materials:
https://www.codesansar.com/numerical-methods/newton-raphson-method-matlab-program-
output.htm
Code:
"""
Name: B K Kiran Kumar
USN: 4SF21CY015
Sem & Dept: 7CY-CSE
Faculty Incharge: Mr. Sunil Kumar K (Assistant Professor)
"""
import numpy as np
import matplotlib.pyplot as plt
Parameters:
f : Function for which the root is to be found.
df : Derivative of the function f(x).
x0 : Initial guess.
tol : Tolerance for stopping criterion (default: 1e-4).
max_iter : Maximum number of iterations (default: 100).
Returns:
root : The approximate root.
"""
x = x0
x_values = [x0]
iterations = [0]
for i in range(max_iter):
fx = f(x)
dfx = df(x)
if dfx == 0:
raise ValueError("Derivative is zero. Newton-Raphson method fails.")
# Check convergence
if abs(x_new - x) < tol:
print(f"Converged in {i+1} iterations.")
return x_new, x_values, iterations
x = x_new
plt.subplot(1, 2, 1)
plt.plot(iterations, x_values, marker='o')
plt.title('Newton-Raphson: Iterations vs X')
plt.xlabel('Iterations')
plt.ylabel('X Value')
plt.grid(True)
plt.subplot(1, 2, 2)
plt.plot(x_range, y_values, label='f(x)')
plt.plot(x_values, [f(x) for x in x_values], 'ro', label='Iterations')
plt.title('Function and Iterations')
plt.xlabel('X')
plt.ylabel('f(x)')
plt.axhline(y=0, color='r', linestyle='--')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()
return root
def main():
# Example with specific function
def f(x):
return x + 0.24674*x - 2467.4011
def df(x):
return 1.24674
if __name__ == "__main__":
main()
Output:
2. Matrix Inversion by Gauss-Siedel Method:
Algorithm:
Reference Material:
https://www.geeksforgeeks.org/gauss-seidel-method/
https://in.mathworks.com/matlabcentral/answers/86085-gauss-seidel-method-in-matlab
Code:
"""
Name: B K Kiran Kumar
USN: 4SF21CY015
DEPT: 7CY-CSE
Faculty Incharge: Mr. Sunil Kumar K (Assistant Professor)
"""
import numpy as np
import matplotlib.pyplot as plt
def get_matrix_input(matrix_type):
"""
Get matrix input from user interactively
"""
while True:
try:
# Get matrix dimensions
rows = int(input(f"Enter number of rows for {matrix_type} matrix: "))
cols = int(input(f"Enter number of columns for {matrix_type} matrix: "))
return matrix
except ValueError:
print("Invalid input. Please enter numeric values.")
x = x0.copy()
errors = []
iterations_details = []
# Gauss-Seidel update
for i in range(n):
# Calculate sigma (sum of known terms)
sigma_left = np.dot(A[i, :i], x[:i]) # Using already updated values
sigma_right = np.dot(A[i, i+1:], x_old[i+1:]) # Using old values for remaining terms
})
# Calculate error
error = np.max(np.abs((x - x_old) / x)) if np.any(x != 0) else np.max(np.abs(x - x_old))
errors.append(error)
# Convergence check
if error < tolerance:
break
def plot_convergence(errors):
"""
Plot convergence of Gauss-Seidel method
"""
plt.figure(figsize=(10, 6))
plt.plot(range(1, len(errors) + 1), errors, marker='o')
plt.title('Gauss-Seidel Method Convergence')
plt.xlabel('Iterations')
plt.ylabel('Relative Error')
plt.yscale('log')
plt.grid(True)
plt.show()
def main():
# Get user inputs
print("Gauss-Seidel Method Solver")
print("-------------------------")
# Flatten b to 1D array
b = b.flatten()
# Get initial guess
print("\n3. Initial Guess Vector (x0)")
x0 = get_matrix_input("Initial Guess")
# Flatten x0 to 1D array
x0 = x0.flatten()
# Solve system
solution, errors, iterations = gauss_seidel(A, b, x0, max_iter, tolerance)
# Plot convergence
plot_convergence(errors)
if __name__ == "__main__":
main()
Output:
MODULE 2
1 Newton’s Forward Difference:
Algorithm:
Step 1: Start the process of constructing the forward difference table.
Step 2: Input the given data: 𝓍 values (independent variable), Corresponding
𝓎 values (dependent variable).
Step 3: Form the table structure: Arrange 𝓍 values in the first column and
𝓎 values in the first row of the table.
Step 4: Compute forward differences:
For each column (starting from the second column):
o Compute the differences between consecutive entries in
the previous column using the formula:
Code:
"""
Name: B K Kiran Kumar
USN: 4SF21CY015
DEPT: 7 CY-CSE
Faculty Incharge: Mr. Sunil Kumar K (Assistant Professor)
"""
import numpy as np
import matplotlib.pyplot as plt
from typing import List, Tuple
class NewtonForwardInterpolation:
def __init__(self, x_data: List[float], y_data: List[float]):
"""
Initialize Newton's Forward Interpolation
Parameters:
x_data: List of x-coordinates
y_data: List of corresponding y-coordinates
"""
self.x_data = np.array(x_data)
self.y_data = np.array(y_data)
self.n = len(x_data)
self.step_size = self.x_data[1] - self.x_data[0]
# Validate inputs
if len(set(np.diff(self.x_data))) > 1:
raise ValueError("Data points must have uniform step size")
Returns:
2D numpy array representing forward differences
"""
# Initialize difference table
diff_table = np.zeros((self.n, self.n))
diff_table[:, 0] = self.y_data
return diff_table
Parameters:
x: Point to interpolate
Returns:
Interpolated y value
"""
# Compute u
u = (x - self.x_data[0]) / self.step_size
# Interpolation polynomial
result = diff_table[0, 0]
factorial = 1
for i in range(1, self.n):
factorial *= i
result += (u * diff_table[0, i]) / factorial
u *= (u - i)
return result
Parameters:
interpolation_point: x-value to interpolate
"""
plt.figure(figsize=(12, 6))
# Interpolation point
interp_y = self.interpolate(interpolation_point)
plt.scatter(interpolation_point, interp_y, color='green',
s=200, marker='*', label='Interpolation Point')
def get_user_inputs():
"""
Collect user inputs interactively
"""
# Data points input
print("Enter data points (x, y)")
x_data, y_data = [], []
while True:
try:
x = float(input("Enter x (or press Enter to finish): "))
y = float(input("Enter corresponding y: "))
x_data.append(x)
y_data.append(y)
except ValueError:
break
# Interpolation point
interpolation_point = float(input("Enter point to interpolate: "))
def main():
# Get user inputs
x_data, y_data, interpolation_point = get_user_inputs()
if __name__ == "__main__":
main()
Output:
2 Lagrange’s Interpolation Formula:
Algorithm:
Step 1:Given a set of 𝑛 data points (𝑥0, 𝑦0),( 𝑥1, 𝑦1),...,( 𝑥𝑛−1, 𝑦𝑛−1) where 𝑥𝑖
are the known 𝑥-coordinates and 𝑦𝑖 are the corresponding 𝑦-coordinates.
Given the point 𝑎 (the value of 𝑥where you want to estimate 𝑦).
Step 2: Set Up Lagrange Polynomial: The Lagrange interpolation polynomial is
given by:
−1
𝑓(𝑎) = ∑𝑛𝑖=0 𝑦𝑖𝐿𝑖(𝑎)
Where 𝐿𝑖(𝑎) is given as
Flowchart:
Code:
"""
Name: B K Kiran Kumar
USN: 4SF21CY015
DEPT: 7 CY-CSE
Faculty Incharge: Mr. Sunil Kumar K (Assistant Professor)
"""
import numpy as np
import matplotlib.pyplot as plt
Parameters:
x_points: list of x coordinates of known points
y_points: list of y coordinates of known points
x: x coordinate for interpolation
Returns:
Interpolated y value
"""
n = len(x_points)
y=0
for i in range(n):
# Calculate Lagrange basis polynomial
p=1
for j in range(n):
if i != j:
p *= (x - x_points[j]) / (x_points[i] - x_points[j])
y += p * y_points[i]
return y
Parameters:
x_points: list of x coordinates of known points
y_points: list of y coordinates of known points
"""
# Create dense interpolation points
x_interp = np.linspace(min(x_points), max(x_points), 200)
y_interp = [lagrange_interpolation(x_points, y_points, x) for x in x_interp]
plt.title('Lagrange Interpolation')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid(True)
plt.show()
def main():
# Input data points
print("Lagrange Interpolation")
print("Enter the number of points:")
n = int(input())
x_points = []
y_points = []
if __name__ == "__main__":
main()
Output:
MODULE 3
1. Trapezoid Method for Numerical Integration:
Algorithm:
Step 1: Start the process.
Step 2: Input the required data.
Enter the lower limit (𝑎) of integration
Enter the upper limit (𝑏) of integration.
Enter the number of subintervals (𝑛)
Step 3: Define the function 𝑓(𝑥)
Step 4: Calculate the step size (ℎ)
𝑏−𝑎
ℎ=
𝑛
Code:
import numpy as np
import matplotlib.pyplot as plt
from typing import Callable, Union
class TrapezoidalIntegration:
def __init__(self, func: Callable[[float], float]):
"""
Initialize Trapezoidal Integration
Parameters:
func: Integrand function f(x)
"""
self.func = func
def integrate(self,
a: float,
b: float,
n: int = 100) -> dict:
"""
Compute definite integral using Trapezoidal Rule
Parameters:
a: Lower integration limit
b: Upper integration limit
n: Number of subintervals
Returns:
Dictionary with integration results
"""
# Validate inputs
if a > b:
a, b = b, a
# Initialize sum
integral_sum = 0.5 * (self.func(a) + self.func(b))
# Final integration
integral_value = h * integral_sum
return {
'integral': integral_value,
'method': 'Trapezoidal Rule',
'subintervals': n,
'absolute_error': absolute_error,
'relative_error': relative_error
}
def _simpson_integration(self,
a: float,
b: float,
n: int) -> float:
"""
Simpson's Rule for error comparison
Parameters:
a: Lower integration limit
b: Upper integration limit
n: Number of subintervals
Returns:
Integral approximation
"""
h = (b - a) / n
def simpson_sum():
integral_sum = self.func(a) + self.func(b)
# Even terms
for i in range(1, n, 2):
x=a+i*h
integral_sum += 4 * self.func(x)
# Odd terms
for i in range(2, n-1, 2):
x=a+i*h
integral_sum += 2 * self.func(x)
return integral_sum * h / 3
return simpson_sum()
def visualize_integration(self,
a: float,
b: float,
n: int = 100):
"""
Visualize Trapezoidal Integration
Parameters:
a: Lower integration limit
b: Upper integration limit
n: Number of subintervals
"""
# Generate smooth function points
x = np.linspace(a, b, 200)
y = [self.func(xi) for xi in x]
# Plotting
plt.figure(figsize=(12, 6))
plt.plot(x, y, label='Function f(x)', color='blue')
plt.fill_between(x_trapezoid, y_trapezoid, alpha=0.3,
color='green', label='Trapezoidal Regions')
def get_user_inputs():
"""
Collect user inputs interactively
"""
# Function selection
print("Select Integration Function:")
print("1. f(x) = x^2")
print("2. f(x) = sin(x)")
print("3. f(x) = exp(x)")
print("4. Custom function")
# Function mapping
functions = {
1: lambda x: x**2,
2: np.sin,
3: np.exp,
}
if choice == 4:
# Custom function input
def custom_func(x):
return eval(input("Enter function in terms of x: "))
func = custom_func
else:
func = functions[choice]
# Integration limits
a = float(input("Enter lower limit (a): "))
b = float(input("Enter upper limit (b): "))
# Number of subintervals
n = int(input("Enter number of subintervals: "))
return func, a, b, n
def main():
# Get user inputs
func, a, b, n = get_user_inputs()
# Perform integration
result = integrator.integrate(a, b, n)
# Print results
print("\n--- Integration Results ---")
for key, value in result.items():
print(f"{key.replace('_', ' ').title()}: {value}")
# Visualize integration
integrator.visualize_integration(a, b, n)
if __name__ == "__main__":
"""
Name: B K Kiran Kumar
USN: 4SF21CY015
DEPT: 7 CY-CSE
Faculty Incharge: Mr. Sunil Kumar K (Assistant Professor)
"""
main()
Output:
2. Simpsons 𝟏Ú𝟑 𝒓𝒅 rule for Numerical Integration:
Algorithm:
Step 1: Start the process.
Step 2: Input the required data.
Enter the lower limit (𝑎) of integration
Enter the upper limit (𝑏) of integration.
Enter the number of subintervals (𝑛)
Step 3: Define the function 𝑓(𝑥)
Step 4: Calculate the step size (ℎ)
𝑏−𝑎
ℎ= 𝑛
Step 5: Compute the initial sum of the boundary values.
Initialize the result as: 𝑟𝑒𝑠𝑢𝑙𝑡 = 𝑓(𝑎) + 𝑓(𝑏)
Step 6: Sum Odd Terms:
Loop through all odd indices from 1 to 𝑛 − 1:
o Compute 𝑥𝑖 = 𝑎 + 𝑖. ℎ
o Add 4.𝑓(𝑥𝑖) to the 𝑟𝑒𝑠𝑢𝑙𝑡
Step 7: Sum Even Terms:
Loop through all odd indices from 2 to 𝑛 − 2:
o Compute 𝑥𝑖 = 𝑎 + 𝑖. ℎ
o Add 2.𝑓(𝑥𝑖) to the 𝑟𝑒𝑠𝑢𝑙𝑡
ℎ
Step 8: Multiply the result by the factor :
3
Code:
"""
Name: B K Kiran Kumar
USN: 4SF21CY015
DEPT: 7 CY-CSE
Faculty Incharge: Mr. Sunil Kumar K (Assistant Professor)
"""
import numpy as np
import matplotlib.pyplot as plt
import math
Parameters:
func: Integration function
a: Lower bound
b: Upper bound
n: Number of subintervals (must be even)
Returns:
Integral approximation
"""
# Ensure even number of subintervals
if n % 2 != 0:
n += 1
h = (b - a) / n
x = np.linspace(a, b, n+1)
y = [func(xi) for xi in x]
return integral, x, y
plt.figure(figsize=(10, 6))
plt.plot(x_smooth, y_smooth, 'b-', label='Function')
plt.fill_between(x, 0, y, alpha=0.3, color='red', label='Integral Area')
return integral
def main():
print("Simpson's 1/3 Rule Integration")
a = float(input())
print("Enter upper bound:")
b = float(input())
if __name__ == "__main__":
main()
Output:
MODULE 4
1 Euler Series Method:
Algorithm:
Step 2: Initialization
Set x0, y0, and create lists to store x-values and y-values.
While x0<xend:
Update y0=y0+h⋅f(x0,y0)
Update x0=x0+h
Append x0 and y0 to the lists.
Step 4: Plotting
Step 5: Output
Step 6: End
Flowchart:
Code:
"""
Name: B K Kiran Kumar
USN: 4SF21CY015
DEPT: 7 CY-CSE
Faculty Incharge: Mr. Sunil Kumar K (Assistant Professor)
"""
def get_differential_equation():
"""
Get the differential equation from the user.
Returns:
callable: A lambda function representing dy/dx.
"""
print("Enter the differential equation dy/dx as a function of x and y (e.g., x + y + x * y):")
eq_str = input()
return lambda x, y: eval(eq_str)
Parameters:
func (callable): Differential equation dy/dx as a function of x and y.
x0 (float): Initial x value.
y0 (float): Initial y value at x0.
h (float): Step size.
x_end (float): Target x value.
Returns:
None
"""
x_values = [x0]
y_values = [y0]
def main():
"""
Main function to get user inputs and solve the differential equation.
"""
print("Euler's Method Numerical Solver")
if __name__ == "__main__":
main()
Output:
2 Runge Kutta 4th Order Method:
Algorithm:
Step 1: Start
Step 2: Define function f(x,y)
Step 3: Read values of initial condition (x0,y0) number of steps nnn, and calculation
point xn
Step 4: Calculate step size h=(xn−x0)/n
Step 5: Set i=0
Step 6: Loop
Compute k1=h⋅f(x0,y0)
Compute k2=h⋅f(x0+h2,y0+k12)
Compute k3=h⋅f(x0+h/2,y0+k2/2)
Compute k4=h⋅f(x0+h,y0+k3)
Compute k=(k1+2k2+2k3+k4)/6
Compute yn=y0+k
Increment i=i+1
Update x0=x0+h
Update y0=yn
Repeat while i<ni < ni<n
Step 7: Display yny_nyn as result
Step 8: Stop
Flowchart:
Code:
"""
Name: B K Kiran Kumar
USN: 4SF21CY015
DEPT: 7 CY-CSE
Faculty Incharge: Mr. Sunil Kumar K (Assistant Professor)
"""
def get_differential_equation():
"""
Get the differential equation from the user.
Returns:
callable: A lambda function representing dy/dx.
"""
print("Enter the differential equation dy/dx as a function of x and y (e.g., (x - y)/2):")
eq_str = input()
return lambda x, y: eval(eq_str)
Parameters:
dydx (callable): Differential equation dy/dx as a function of x and y.
x0 (float): Initial x value.
y0 (float): Initial y value at x0.
x (float): Target x value.
h (float): Step size.
Returns:
float: Approximate value of y at x.
"""
# Calculate the number of steps
n = int((x - x0) / h)
y = y0
return y
def main():
"""
Main function to get inputs from the user and solve the differential equation.
"""
print("Runge-Kutta 4th Order Method Solver")
if __name__ == "__main__":
main()
Output:
MODULE 5
1 Laplace Equation Method:
Algorithm:
Step 1: Input Requirements
Set boundary conditions (top, bottom, left, right).
Initialize interior points (U1 to U9) to 0.
Set tolerance (1e-4) and max iterations (1000).
Step 2: Initialize Grid
Create a 3x3 grid for U.
Step 3: Iterative Process
For each iteration:
o Copy current grid to U_old.
o Update interior points (U1 to U9) using Laplace's equation.
Step 4: Convergence Check
If the maximum change between the old and new grid is less than tolerance, stop.
Step 5: Termination
If max iterations are reached without convergence, stop.
Step 6: Output
Print the final grid values.
Flowchart:
Code:
"""
Name: B K Kiran Kumar
USN: 4SF21CY015
DEPT: 7 CY-CSE
Faculty Incharge: Mr. Sunil Kumar K (Assistant Professor)
"""
import numpy as np
# Iterative process
for iteration in range(max_iterations):
U_old = U.copy()
Get grid size (nx, ny) and source function f(x,y) from the user.
Initialize vector bb and populate it with the evaluated source term for interior points.
Step 9: End
Code:
"""
Name: B K Kiran Kumar
USN: 4SF21CY015
DEPT: 7 CY-CSE
Faculty Incharge: Mr. Sunil Kumar K (Assistant Professor)
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.sparse import diags
from scipy.sparse.linalg import spsolve
"""
Poisson Equation Solver in 2D
Functions:
1. poisson_solver_2d(nx, ny, source_func):
Solves the 2D Poisson equation using a sparse matrix representation
of the discretized grid.
Parameters:
nx : Number of grid points in the x-direction.
ny : Number of grid points in the y-direction.
source_func : Function defining the source term f(x, y).
Returns:
X, Y : Mesh grid for the solution domain.
solution_grid : Solution of the Poisson equation as a 2D array.
2. plot_poisson_solution(X, Y, solution):
Visualizes the solution using contour and surface plots.
3. main():
Accepts user input for grid size and source function, solves the
Poisson equation, and visualizes the solution.
"""
x = np.linspace(0, 1, nx)
y = np.linspace(0, 1, ny)
X, Y = np.meshgrid(x, y)
b = np.zeros((nx*ny))
for i in range(1, nx-1):
for j in range(1, ny-1):
idx = i + j*nx
b[idx] = source_func(X[j,i], Y[j,i]) * (dx*dy)
b[0:nx] = 0
b[-nx:] = 0
b[::nx] = 0
b[nx-1::nx] = 0
solution = spsolve(A, b)
solution_grid = solution.reshape((ny, nx))
return X, Y, solution_grid
def main():
print("Enter grid size (nx ny):")
nx, ny = map(int, input().split())
if __name__ == "__main__":
main()
Code 2:
import numpy as np
# Left neighbor
if (i, j - 1) in point_indices:
# Right neighbor
if (i, j + 1) in point_indices:
A[idx, point_indices[(i, j + 1)]] = 1
else:
b[idx] -= right_boundary[i] # Contribution from right boundary
# Top neighbor
if (i - 1, j) in point_indices:
A[idx, point_indices[(i - 1, j)]] = 1
else:
b[idx] -= top_boundary[j] # Contribution from top boundary
# Bottom neighbor
if (i + 1, j) in point_indices:
A[idx, point_indices[(i + 1, j)]] = 1
else:
b[idx] -= bottom_boundary[j] # Contribution from bottom boundary
Output:
Code 2 Output: