0% found this document useful (0 votes)
4 views12 pages

NM Lab Python

The document outlines various numerical methods including the Bisection Method, Newton Forward Interpolation, Lagrange Interpolation, Least Squares Method, and integration techniques such as the Trapezoidal Rule and Simpson's Rule. Each method is accompanied by an algorithm and a corresponding Python program for implementation. The document serves as a comprehensive guide for solving mathematical problems using these numerical methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

NM Lab Python

The document outlines various numerical methods including the Bisection Method, Newton Forward Interpolation, Lagrange Interpolation, Least Squares Method, and integration techniques such as the Trapezoidal Rule and Simpson's Rule. Each method is accompanied by an algorithm and a corresponding Python program for implementation. The document serves as a comprehensive guide for solving mathematical problems using these numerical methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Bisec&on Method

Algorithm

1. Define the function f(x).


2. Choose initial values a and b such that f(a)⋅f(b)<0.
3. Set tolerance ε and maximum iterations N.
4. For each iteration (up to N):
5. Calculate midpoint c=a+b/2.
6. If ∣f(c)∣<ε or b−a/2<ε, stop and return c.
7. If f(a)⋅f(c)<0, set b=c
8. Else, set a=c.
5. End loop and return final c as root approximation.

Program

def f(x):
return x**3 - x - 2
def bisec5on(a, b, tol, max_iter):
if f(a) * f(b) >= 0:
print("Invalid interval: f(a) * f(b) must be < 0")
return None
print("\n{:<10} {:<12} {:<12} {:<12} {:<12}".format("Iter", "a", "b", "c", "f(c)"))
print("-" * 58)
for i in range(1, max_iter + 1):
c = (a + b) / 2
fc = f(c)
print("{:<10} {:<12.6f} {:<12.6f} {:<12.6f} {:<12.6f}".format(i, a, b, c, fc))
if abs(fc) < tol or abs(b - a) / 2 < tol:
print(f"\nRoot found at x = {c:.6f} aQer {i} itera5ons.")
return c
if f(a) * fc < 0:
b=c
else:
a=c
print("\nMaximum itera5ons reached.")
return (a + b) / 2
print("Bisec5on Method to find root of f(x) = x^3 - x - 2")
a = float(input("Enter value of a (lower bound): "))
b = float(input("Enter value of b (upper bound): "))
tol = float(input("Enter tolerance (e.g. 0.0001): "))
max_iter = int(input("Enter maximum number of itera5ons: "))
root = bisec5on(a, b, tol, max_iter)
if root is not None:
print("Approximate root is:", root)

Newton Forward Interpola&on Algorithm

1 Input number of data points n, and arrays x[i] and y[i].

2 Compute forward difference table for y[i].

3 Calculate h=x[1]−x[0] (uniform spacing).

4 Compute u=x−x0/h.

5 Initialize result P=y0.

6 For each i=11 to n−1:


7. Compute the term:
term=(u(u−1)(u−2)…(u−i+1))/i!× Δiy0
8. Add term to result: P=P+term

9 Output the final interpolated value P.

Proagram
import math
def forward_difference_table(y, n):
diff_table = [y.copy()]
for i in range(1, n):
row = []
for j in range(n - i):
val = diff_table[i - 1][j + 1] - diff_table[i - 1][j]
row.append(val)
diff_table.append(row)
return diff_table
def u_term(u, i):
result = 1
for k in range(i):
result *= (u - k)
return result
def newton_forward_interpola5on(x_vals, y_vals, x):
n = len(x_vals)
h = x_vals[1] - x_vals[0] # assuming equal spacing
u = (x - x_vals[0]) / h
diff_table = forward_difference_table(y_vals, n)
result = y_vals[0] # y0
for i in range(1, n):
term = (u_term(u, i) * diff_table[i][0]) / math.factorial(i)
result += term
return result
n = int(input("Enter number of data points: "))
x_vals = []
y_vals = []
print("Enter the x and y values:")
for i in range(n):
x = float(input(f"x[{i}]: "))
y = float(input(f"y[{i}]: "))
x_vals.append(x)
y_vals.append(y)
x_to_interpolate = float(input("Enter the value of x to interpolate: "))
interpolated_value = newton_forward_interpola5on(x_vals, y_vals, x_to_interpolate)
print(f"\nInterpolated value at x = {x_to_interpolate} is: {interpolated_value:.6f}")

Algorithm Lagrange Interpola&on

1 Input number of data points n, and arrays x[i], y[i].

2 Input the value of x where interpolation is required.

3 Initialize yinterp=0.

4 For each i=0 to n−1:


5 Initialize Li=1.
6 For each j=0 to n−1, j≠i:
7 Compute Li=Li×(x−xj)/(xi−xj)
8 Multiply Li with y[i], and add to yinterp:
yinterp+=Li×y[i]

9 Output yinterp as the interpolated value.

Program
def lagrange_interpola5on(x_vals, y_vals, x):
n = len(x_vals)
y_interp = 0 # Ini5alize result
for i in range(n):
L_i = 1
for j in range(n):
if i != j:
L_i *= (x - x_vals[j]) / (x_vals[i] - x_vals[j])
y_interp += L_i * y_vals[i]
return y_interp

n = int(input("Enter number of data points: "))


x_vals = []
y_vals = []
print("Enter the x and y values:")
for i in range(n):
x = float(input(f"x[{i}]: "))
y = float(input(f"y[{i}]: "))
x_vals.append(x)
y_vals.append(y)
x_to_interpolate = float(input("Enter the value of x to interpolate: "))
interpolated_value = lagrange_interpola5on(x_vals, y_vals, x_to_interpolate)
print(f"\nInterpolated value at x = {x_to_interpolate} is: {interpolated_value:.6f}")

Least Square Method Algorithm

1. Input number of data points nn, and arrays x[i], y[i].


2. Compute the sums:
Sx=∑xi,
Sy=∑yi,
Sxy=∑xiyi,
Sx2=∑x2i
3. Calculate slope b using:

b=nSxy−SxSy/nSx2−(Sx)

4. Calculate intercept a using:


a=Sy−bSx/n

5. The required least squares line is:

y=a+bx

6. Output values of a and b

Program
def least_squares_fit(x_vals, y_vals):
n = len(x_vals)
Sx = sum(x_vals)
Sy = sum(y_vals)
Sxy = sum(x * y for x, y in zip(x_vals, y_vals))
Sx2 = sum(x * x for x in x_vals)
b = (n * Sxy - Sx * Sy) / (n * Sx2 - Sx * Sx)
a = (Sy - b * Sx) / n
return a, b
n = int(input("Enter number of data points: "))
x_vals = []
y_vals = []
print("Enter the x and y values:")
for i in range(n):
x = float(input(f"x[{i+1}]: "))
y = float(input(f"y[{i+1}]: "))
x_vals.append(x)
y_vals.append(y)
a, b = least_squares_fit(x_vals, y_vals)
print(f"\nThe best fit line is: y = {a:.4f} + {b:.4f}x")

Algorithm for Trapezoidal Rule


1. Start
2. Define function f(x)
3. Read lower limit of integration, upper limit of integration
and number of sub interval
4. Calcultae: step size = (upper limit - lower limit)/number of
sub interval

5. Set: integration value = f(lower limit) + f(upper limit)


6. Set: i = 1
7. If i > number of sub interval then goto
8. Calculate: k = lower limit + i * h
9. Calculate: Integration value = Integration Value + 2* f(k)
10. Increment i by 1 i.e. i = i+1 and go to step 7
11. Calculate: Integration value = Integration value * step
size/2
12. Display Integration value as required answer
13. Stop
Program
# Define the func5on to integrate
def f(x):
return x**2 # Example: f(x) = x^2
def trapezoidal_rule(a, b, n):
h = (b - a) / n
result = f(a) + f(b)
for i in range(1, n):
x=a+i*h
result += 2 * f(x)
result *= h / 2
return result
print("Trapezoidal Rule to approximate ∫f(x) dx")
a = float(input("Enter lower limit a: "))
b = float(input("Enter upper limit b: "))
n = int(input("Enter number of subintervals n: "))
approx_integral = trapezoidal_rule(a, b, n)
print(f"\nApproximate value of integral: {approx_integral:.6f}")

Simpson 1/3 Algorithm


. Start
2. Define function f(x)
3. Read lower limit of integration, upper limit of
integration and number of sub interval
4. Calcultae: step size = (upper limit - lower limit)/number of
sub interval
5. Set: integration value = f(lower limit) + f(upper limit)
6. Set: i = 1
7. If i > number of sub interval then goto
8. Calculate: k = lower limit + i * h
9. If i mod 2 =0 then
Integration value = Integration Value + 2* f(k)
Otherwise
Integration Value = Integration Value + 4 * f(k)
End If

10. Increment i by 1 i.e. i = i+1 and go to step 7


11. Calculate: Integration value = Integration value * step
size/3
12. Display Integration value as required answer
13. Stop
Program
# Define the func5on to integrate
def f(x):
return x**2 # Example: f(x) = x^2
def simpsons_one_third(a, b, n):
if n % 2 != 0:
print("Error: Number of subintervals (n) must be even.")
return None
h = (b - a) / n
result = f(a) + f(b)
for i in range(1, n):
x=a+i*h
if i % 2 == 0:
result += 2 * f(x)
else:
result += 4 * f(x)
result *= h / 3
return result
print("Simpson's 1/3 Rule to approximate ∫f(x) dx")
a = float(input("Enter lower limit a: "))
b = float(input("Enter upper limit b: "))
n = int(input("Enter even number of subintervals n: "))
approx_integral = simpsons_one_third(a, b, n)
if approx_integral is not None:
print(f"\nApproximate value of integral: {approx_integral:.6f}")

Simpson 3/8 Rule Algorithm


. Start
2. Define function f(x)
3. Read lower limit of integration, upper limit of
integration and number of sub interval
4. Calcultae: step size = (upper limit - lower limit)/number of
sub interval
5. Set: integration value = f(lower limit) + f(upper limit)
6. Set: i = 1
7. If i > number of sub interval then goto
8. Calculate: k = lower limit + i * h
9. If i mod 3 =0 then
Integration value = Integration Value + 2* f(k)
Otherwise
Integration Value = Integration Value + 3 * f(k)
End If
10. Increment i by 1 i.e. i = i+1 and go to step 7
11. Calculate: Integration value = Integration value * step
size*3/8
12. Display Integration value as required answer
13. Stop

Program
def f(x):
return x**2
def simpsons_three_eighth(a, b, n):
if n % 3 != 0:
print("Error: Number of subintervals (n) must be a mul5ple of 3.")
return None
h = (b - a) / n
result = f(a) + f(b)
for i in range(1, n):
x=a+i*h
if i % 3 == 0:
result += 2 * f(x)
else:
result += 3 * f(x)

result *= (3 * h / 8)
return result
print("Simpson's 3/8 Rule to approximate ∫f(x) dx")
a = float(input("Enter lower limit a: "))
b = float(input("Enter upper limit b: "))
n = int(input("Enter number of subintervals n (must be mul5ple of 3): "))
approx_integral = simpsons_three_eighth(a, b, n)
if approx_integral is not None:
print(f"\nApproximate value of integral: {approx_integral:.6f}")

R-K 1st Order Differen&al Equa&on

1 Input function f(x,y), initial values x0,y0, step size h, number of steps n.

2 For i=0to n−1:


3. Compute k1=h⋅f(xi,yi)
4. Compute k2=h⋅f(xi+h/2,yi+k1/2)
5. Compute k3=h⋅f(xi+h/2,yi+k2/2)
6. Compute k4=h⋅f(xi+h,yi+k3)
7. Update yi+1=yi+16(k1+2k2+2k3+k4)
8. Update xi+1=xi+h

9 Repeat until desired value of x is reached


10 Output yn as the approximate solution

R-K 1st Order Differen&al Equa&on


def f(x, y):
return x + y # Example: dy/dx = x + y
def runge_kuma_4(x0, y0, h, n):
print(f"{'Step':<5}{'x':<10}{'y':<15}")
print("-" * 30)
for i in range(n):
k1 = h * f(x0, y0)
k2 = h * f(x0 + h / 2, y0 + k1 / 2)
k3 = h * f(x0 + h / 2, y0 + k2 / 2)
k4 = h * f(x0 + h, y0 + k3)
y0 = y0 + (1 / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
x0 = x0 + h
print(f"{i+1:<5}{x0:<10.4f}{y0:<15.6f}")
return y0
print("Runge-Kuma 4th Order Method for dy/dx = f(x, y)")
x0 = float(input("Enter ini5al x (x0): "))
y0 = float(input("Enter ini5al y (y0): "))
h = float(input("Enter step size h: "))
n = int(input("Enter number of steps: "))
y_final = runge_kuma_4(x0, y0, h, n)
print(f"\nApproximate solu5on at x = {x0 + n * h} is y = {y_final:.6f}")

R-K Second Order Differen&al Equa&on

1 Input f(x,y,y′) initial values x0,y0,y0′, step size h, number of steps n.

2 Let y1=y, y2=y′.

3 For each step i=1 to n:


4. Compute:
k1=h⋅y2
l1=h⋅f(x,y1,y2)
5. Compute:
k2=h⋅(y2+l1/2)
l2=h⋅f(x+h/2,y1+k1/2,y2+l1/2)
6. Compute:
k3=h⋅(y2+l2/2)
l3=h⋅f(x+h/2,y1+k2/2,y2+l2/2)
7. Compute:
k4=h⋅(y2+l3)
l4=h⋅f(x+h,y1+k3,y2+l3)
8. Update:
y1=y1+16(k1+2k2+2k3+k4)
y2=y2+16(l1+2l2+2l3+l4)
x=x+hx

9. Repeat steps until desired x is reached.

10. Output final y1 as the approximate solution.

Program
# Define the second-order ODE in the form d²y/dx² = f(x, y, y')
def f(x, y, dy):
return -y # Example: d²y/dx² = -y (Simple Harmonic Mo5on)
# Runge-Kuma 4th Order Method for Second-Order ODEs
def rk4_second_order(x0, y0, dy0, h, n):
print(f"{'Step':<5}{'x':<10}{'y':<15}{'y\'':<15}")
print("-" * 45)
for i in range(n):
k1 = h * dy0
l1 = h * f(x0, y0, dy0)
k2 = h * (dy0 + l1 / 2)
l2 = h * f(x0 + h/2, y0 + k1 / 2, dy0 + l1 / 2)
k3 = h * (dy0 + l2 / 2)
l3 = h * f(x0 + h/2, y0 + k2 / 2, dy0 + l2 / 2)
k4 = h * (dy0 + l3)
l4 = h * f(x0 + h, y0 + k3, dy0 + l3)
y0 += (k1 + 2*k2 + 2*k3 + k4) / 6
dy0 += (l1 + 2*l2 + 2*l3 + l4) / 6
x0 += h
print(f"{i+1:<5}{x0:<10.4f}{y0:<15.6f}{dy0:<15.6f}")
return y0
print("RK4 Method for Second-Order Differen5al Equa5on d²y/dx² = f(x, y, y')")
x0 = float(input("Enter ini5al x (x0): "))
y0 = float(input("Enter ini5al y (y0): "))
dy0 = float(input("Enter ini5al y' (dy/dx at x0): "))
h = float(input("Enter step size h: "))
n = int(input("Enter number of steps: "))
final_y = rk4_second_order(x0, y0, dy0, h, n)
print(f"\nApproximate solu5on at x = {x0 + n*h:.4f} is y = {final_y:.6f}")

Laplace Equa&on using Gauss Seidel Method


def gauss_seidel_laplace(grid_size, max_iter, tol):
u = [[0.0 for _ in range(grid_size)] for _ in range(grid_size)]
# Set boundary condi5ons (example: top = 100, others = 0)
for i in range(grid_size):
u[0][i] = 100.0 # Top boundary
for it in range(max_iter):
max_diff = 0.0
for i in range(1, grid_size - 1):
for j in range(1, grid_size - 1):
old_u = u[i][j]
u[i][j] = 0.25 * (u[i+1][j] + u[i-1][j] + u[i][j+1] + u[i][j-1])
diff = abs(u[i][j] - old_u)
if diff > max_diff:
max_diff = diff
if max_diff < tol:
print(f"\nConverged in {it+1} itera5ons.\n")
break
return u
print("Solving Laplace's Equa5on using Gauss-Seidel Method")
N = int(input("Enter grid size (e.g., 5 for 5x5 grid): "))
MAX_ITER = int(input("Enter maximum number of itera5ons: "))
TOL = float(input("Enter tolerance (e.g., 0.0001): "))
solu5on = gauss_seidel_laplace(N, MAX_ITER, TOL)
# Display solu5on grid
print("\nSolu5on Grid:")
for row in solu5on:
print(" ".join(f"{val:8.4f}" for val in row))

Poisson Equa&on using Gauss Seidel Itera&on


def f(x, y):
return -10 # Example: constant source term
def gauss_seidel_poisson(nx, ny, max_iter, tol):
# Domain size and grid spacing
Lx, Ly = 1.0, 1.0
dx = Lx / (nx - 1)
dy = Ly / (ny - 1)
h2 = dx * dx # Assume dx = dy
# Ini5alize u and grid
u = [[0.0 for _ in range(ny)] for _ in range(nx)]
x_vals = [i * dx for i in range(nx)]
y_vals = [j * dy for j in range(ny)]
for it in range(max_iter):
max_diff = 0.0
for i in range(1, nx - 1):
for j in range(1, ny - 1):
rhs = f(x_vals[i], y_vals[j])
old_u = u[i][j]
u[i][j] = 0.25 * (u[i+1][j] + u[i-1][j] + u[i][j+1] + u[i][j-1] - h2 * rhs)
diff = abs(u[i][j] - old_u)
max_diff = max(max_diff, diff)
if max_diff < tol:
print(f"\nConverged in {it+1} itera5ons.\n")
break
return u
print("Solving Poisson's Equa5on using Gauss-Seidel Itera5on")
nx = int(input("Enter number of grid points in x-direc5on (e.g., 5): "))
ny = int(input("Enter number of grid points in y-direc5on (e.g., 5): "))
max_iter = int(input("Enter maximum number of itera5ons: "))
tol = float(input("Enter convergence tolerance (e.g., 0.0001): "))
solu5on = gauss_seidel_poisson(nx, ny, max_iter, tol)
# Display the solu5on grid
print("\nSolu5on Grid:")
for row in solu5on:
print(" ".join(f"{val:8.4f}" for val in row))

You might also like