Maths Final Report
Maths Final Report
ASSIGNMENT REPORT on
Submitted by
Shalini L 4SF21CS144
BACHELOR OF ENGINEERING
in
at
Flowchart
Code:
#Name: Shalini L
#USN : 4SF21CS144
#Course Name : Numerical Methods And Applications
def gauss_elimination(matrix):
n = len(matrix)
# Forward elimination (convert matrix to upper triangular form)
for k in range(n):
# Partial pivoting: find the row with the largest element in column k
max_row = max(range(k, n), key=lambda i: abs(matrix[i][k]))
matrix[k], matrix[max_row] = matrix[max_row], matrix[k]
for i in range(k + 1, n):
factor = matrix[i][k] / matrix[k][k]
for j in range(k, n + 1): # Including the last column (right-hand side)
matrix[i][j] -= factor * matrix[k][j]
# Back substitution (solve for the variables)
x = [0] * n
x[n - 1] = matrix[n - 1][n] / matrix[n - 1][n - 1]
for i in range(n - 2, -1, -1):
x[i] = matrix[i][n]
for j in range(i + 1, n):
x[i] -= matrix[i][j] * x[j]
x[i] /= matrix[i][i]
return x
def main():
# Input the number of equations
n = 3 # Here we assume a 3x3 system of equations
# Input the augmented matrix for the system of equations
print("Enter the augmented matrix (coefficients and constants):")
matrix = []
for i in range(n):
row = list(map(float, input().split()))
matrix.append(row)
# Perform Gauss Elimination to solve the system
solution = gauss_elimination(matrix)
# Display the result
print("The solution is:")
for i in range(n):
print(f"x[{i + 1}] = {solution[i]:.2f}")
if __name__ == "__main__":
main()
Output:
2. Gauss-Jacobi method
Algorithm for Gauss-Jacobi method
1. Start
2. Declare the variables and read the order of the matrix n
3. Read the stopping criteria er
4. Read the coefficients aim as
Do for i=1 to n
Do for j=1 to n
Read a[i][j]
Repeat for j
Repeat for i
5. Read the coefficients b[i] for i=1 to n
6. Initialize x0[i] = 0 for i=1 to n
7. Set key=0
8. For i=1 to n
Set sum = b[i]
For j=1 to n
If (j not equal to i)
Set sum = sum – a[i][j] * x0[j]
Repeat j
x[i] = sum/a[i][i]
If absolute value of ((x[i] – x0[i]) / x[i]) > er, then
Set key = 1
Set x0[i] = x[i]
Repeat i
9. If key = 1, then
Goto step 6
10. Otherwise print results
Flowchart
Code:
#Name: Shalini L
#USN : 4SF21CS144
#Course Name : Numerical Methods And Applications
import numpy as np
# Initialize the solution vector x with zeros (or any initial guess)
n = len(b)
x = np.zeros(n)
# Iterative process
for iteration in range(max_iterations):
x_new = np.zeros_like(x)
def main():
# Example system of equations:
# 4x - x + 2z = 4
# 3x + 5y - 2z = 3
# 2x - y + 3z = 7
A=[
[4, -1, 2],
[3, 5, -2],
[2, -1, 3]
]
b = [4, 3, 7]
Output:
MODULE 2
1.Newtons Forward Interpolation Method
Algorithms for Newtons Forward Interpolation Method
Step 1: Start the program
Step 2: Read n (No. of arguments)
Step 3: For i = 0 to n − 1
Read x i &y i [0]
End i
Step 4: Construct the Forward Difference Table
For j = 1 to n − 1
For i = 0 to n − 1 − j
y i [j] = y[i + 1][j − 1] − y[i][j − 1]
End i
End j
Step 5: Print the Forward Difference Table
For i = 0 to n − 1
For j = 0 to n − 1 − i
Print y i [j]
End j
Next Line
End i
Step 6: Read a (Point of Interpolation)
Step 7: Assign h = x[1] − x[0] (Step Length)
Step 8: Assign u = (a − x[0])/h
Step 9: Assign sum = y 0 [0] & p = 1.0
Step 10: For j = 1 to n − 1
p = p ∗ (u − j + 1)/j
sum = sum + p ∗ y 0 [j]
End j
Step 11: Display a & sum
Step 12: Stop
Flowchart
Code:
#Name: Shalini L
#USN : 4SF21CS144
#Course Name : Numerical Methods And Applications
Parameters:
x_values (list): List of evenly spaced x values.
y_values (list): List of corresponding f(x) values.
target_x (float): The x value for which f(x) needs to be interpolated.
Returns:
float: Interpolated value of f(x) at target_x.
"""
n = len(x_values)
# Step 2: Calculate u
h = x_values[1] - x_values[0] # Spacing between x values
u = (target_x - x_values[0]) / h
return result
# Example usage
if __name__ == "__main__":
# Input data
x_values = [1, 2, 3, 4, 5] # x values
y_values = [1, 8, 27, 64, 125] # Corresponding f(x) values (f(x) = x^3)
target_x = 3.5 # Value of x to interpolate
interpolated_value = newton_forward_difference(x_values, y_values, target_x)
print(f"Interpolated value at x = {target_x}: {interpolated_value:.6f}")
Output:
Flowchart:
Code:
#Name: Shalini L
#USN : 4SF21CS144
#Course Name : Numerical Methods And Applications
Output:
2.Lagrange Method
Algorithm:
1. Start
2. Input: Ask the user for the number of known data.
3. Input: Ask the user to input values of x and corresponding y. Store these values in arrays
x[] and y[] respectively.
4. Display: Show the input data of x[] and y[] to the user so that they can correct any incorrect
data or re-input any missing data.
5. Input: Ask the user to input the value of x at which the value of y is to be interpolated
(x_input).
6. Compute:
o Initialize y_result = 0.
o For i = 0 to n-1:
▪ Initialize term = 1.
▪ For j = 0 to n-1 (where j ≠ i):
▪ Compute term *= (x_input - x[j]) / (x[i] - x[j]).
▪ Update y_result += y[i] * term.
7. Output: Display the value of y_result corresponding to x_input.
8. Input: Ask the user to input 1 to run the program again.
9. If the user inputs 1, go back to step 2. Otherwise, proceed to step 10.
10. End
Code:
#Name: Shalini L
#USN : 4SF21CS144
#Course Name : Numerical Methods And Applications
import numpy as np
def lagrange_interpolation(x_points, y_points, x):
"""
Perform Lagrange interpolation to find the value of the polynomial at a given point.
Parameters:
x_points (list or ndarray): The x-coordinates of the data points.
y_points (list or ndarray): The y-coordinates of the data points.
x (float): The x-value at which the interpolation is to be evaluated.
Returns:
float: The interpolated y-value corresponding to x.
"""
n = len(x_points)
result = 0.0
for i in range(n):
# Calculate the Lagrange basis polynomial L_i(x)
term = y_points[i]
for j in range(n):
if j != i:
term *= (x - x_points[j]) / (x_points[i] - x_points[j])
# Add the term to the result
result += term
return result
# Example Usage
x_points = np.array([1, 2, 3])
y_points = np.array([1, 4, 9]) # This is y = x^2, for example
x_value = 2.5 # The x-value where we want to interpolate
interpolated_value = lagrange_interpolation(x_points, y_points, x_value)
print(f"Interpolated value at x = {x_value}: {interpolated_value}")
Output:
MODULE 3
1.Trapezoidal Method
Algorithm for Trapezoidal Method
o Start
Flowchart
Code:
#Name: Shalini L
#USN : 4SF21CS144
#Course Name : Numerical Methods And Applications
import numpy as np
Parameters:
f (function): The integrand, a function of x.
a (float): The lower limit of integration.
b (float): The upper limit of integration.
Returns:
float: The approximated integral of f from a to b.
"""
# Apply the Trapezoidal Rule formula
integral = (b - a) / 2 * (f(a) + f(b))
return integral
# Example Usage
def example_function(x):
return np.sin(x) # Example: f(x) = sin(x)
result = trapezoidal_rule(example_function, a, b)
Code:
#Name: Shalini L
#USN : 4SF21CS144
#Course Name : Numerical Methods And Applications
# Compute the sum for odd indexed terms (excluding the first and last term)
for i in range(1, n, 2):
sum_odd += f(a + i * h)
# Compute the sum for even indexed terms (excluding the first and last term)
for i in range(2, n, 2):
sum_even += f(a + i * h)
return result
# Example usage:
import math
# Integration limits
a=0
b = math.pi
Flowchart:
Code:
#Name: Shalini L
#USN : 4SF21CS144
#Course Name : Numerical Methods And Applications
import math
# Update x and y
x += h
y = y_next
return x, y
# Example usage:
y0 = 1 # Initial condition y(0) = 1
x0 = 0 # Initial x value
h = 0.1 # Step size
steps = 10 # Number of iterations
Output:
2.Eulars method
Algorithm
1. Start
2. Define function
3. Get the values of x0, y0, h and xn
*Here x0 and y0 are the initial conditions
h is the interval
xn is the required value
4. n = (xn – x0)/h + 1
5. Start loop from i=1 to n
6. y = y0 + h*f(x0,y0)
x=x+h
7. Print values of y0 and x0
8. Check if x < xn
If yes, assign x0 = x and y0 = y
If no, goto 9.
9. End loop i
10. Stop
Flowchart
Code:
#Name: Shalini L
#USN : 4SF21CS144
#Course Name : Numerical Methods And Applications
Parameters:
f (function): Function defining the ODE dy/dx = f(x, y).
x0 (float): Initial x value.
y0 (float): Initial y value.
h (float): Step size.
n (int): Number of steps.
Returns:
list: List of (x, y) values approximating the solution.
"""
results = [(x0, y0)] # Store initial values
for _ in range(n):
# Current values
x, y = results[-1]
# Compute the next value using Euler's formula
y_next = y + h * f(x, y)
x_next = x + h
# Append the result
results.append((x_next, y_next))
return results
# Example usage
if __name__ == "__main__":
# Define the ODE dy/dx = f(x, y)
def f(x, y):
return y - x**2 + 1 # Example: dy/dx = y - x^2 + 1
# Initial conditions
x0 = 0 # Initial x
y0 = 0.5 # Initial y
h = 0.2 # Step size
n = 10 # Number of steps
Output:
MODULE 5
1. Laplace Method
Algorithm for Solving the Laplace Equation
Step 1: Start
Step 2: Input the number of grid points in the x-direction (nx) and the y-direction (ny).
Step 3: Input the tolerance (tol) for convergence and the maximum number of iterations (max_iter).
Step 4: Initialize the grid:
• Create a grid with ny rows and nx columns, initializing all values to 0.
• If the maximum difference is smaller than the tolerance (tol), print "Converged" and stop
the iteration.
Step 7: Check for maximum iterations:
• If the iteration reaches max_iter without convergence, print "Maximum iterations reached
without convergence" and stop.
Step 8: Return the final grid with the solution to the Laplace equation.
Step 9: End
Flowchart:
Code:
import numpy as np
Parameters:
nx (int): Number of grid points in the x-direction.
ny (int): Number of grid points in the y-direction.
tol (float): Convergence tolerance.
max_iter (int): Maximum number of iterations.
Returns:
np.ndarray: Solution grid for the Laplace equation.
"""
# Initialize the solution grid
u = np.zeros((ny, nx))
# Boundary conditions
u[0, :] = 1 # Top boundary
u[-1, :] = 0 # Bottom boundary
u[:, 0] = 0 # Left boundary
u[:, -1] = 0 # Right boundary
# Iterative solver
for iteration in range(max_iter):
u_old = u.copy()
# Update interior points using the finite difference formula
for i in range(1, ny-1):
for j in range(1, nx-1):
u[i, j] = 0.25 * (u_old[i+1, j] + u_old[i-1, j] + u_old[i, j+1] + u_old[i, j-1])
# Example usage
if __name__ == "__main__":
nx, ny = 20, 20 # Grid size
solution = laplace_solver(nx, ny)
# Print the solution
print("Solution grid:")
print(solution)
# Visualization
try:
import matplotlib.pyplot as plt
plt.imshow(solution, origin="lower", cmap="viridis", extent=[0, 1, 0, 1])
plt.colorbar(label="u(x, y)")
plt.title("Solution to Laplace's Equation")
plt.xlabel("x")
plt.ylabel("y")
plt.show()
except ImportError:
print("Matplotlib not installed. Skipping visualization.")
Output:
2.Poissons method
Code:
import numpy as np
# Iterative solver
for iteration in range(max_iter):
u_old = u.copy()
# Update interior points using the finite difference formula
for i in range(1, ny-1):
for j in range(1, nx-1):
u[i, j] = 0.25 * (u_old[i+1, j] + u_old[i-1, j] + u_old[i, j+1] + u_old[i, j-1] - h**2 * F[i, j])
return u
# Example usage
if __name__ == "__main__":
# Define the source term f(x, y)
def f(x, y):
return 2 * np.pi**2 * np.sin(np.pi * x) * np.sin(np.pi * y) # Example: 2*pi^2 * sin(pi*x) *
sin(pi*y)
# Grid size
nx, ny = 40, 40 # Higher resolution grid
# Solve the Poisson equation
solution = poisson_solver(nx, ny, f)
# Print the solution
print("Solution grid:")
print(solution)
Output: