0% found this document useful (0 votes)
19 views13 pages

ME685 Assign2 210769-1

The document contains code and solutions for various computational problems, including regression analysis, Romberg integration, and solving a system of equations using Gaussian elimination. It features Python code for plotting, numerical integration, and optimization techniques. Additionally, it includes pseudo code for Romberg integration and detailed explanations of the methods used.
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)
19 views13 pages

ME685 Assign2 210769-1

The document contains code and solutions for various computational problems, including regression analysis, Romberg integration, and solving a system of equations using Gaussian elimination. It features Python code for plotting, numerical integration, and optimization techniques. Additionally, it includes pseudo code for Romberg integration and detailed explanations of the methods used.
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/ 13

ME685

Princy Chauhan
210769

Ques. 1
a) Code:

import numpy as np

import matplotlib.pyplot as plt

T = np.array([20, 70, 120, 170, 220, 270, 320, 370, 420, 470, 520])

ln_alpha = np.array([-11.42, -11.40, -11.39, -11.37, -11.38, -11.36, -11.35, -


11.35, -11.33, -11.32, -11.31])

X = T - 20

Y = ln_alpha

X_mean = np.mean(X)

Y_mean = np.mean(Y)

numerator = np.sum((X - X_mean) * (Y - Y_mean))

denominator = np.sum((X - X_mean) ** 2)

a1 = numerator / denominator

A = Y_mean - a1 * X_mean

a0 = np.exp(A)

Y_pred = a1 * X + A

SS_res = np.sum((Y - Y_pred) ** 2)

SS_tot = np.sum((Y - Y_mean) ** 2)


r2 = 1 - (SS_res / SS_tot)

print(f"a0 = {a0:.6e}")

print(f"a1 = {a1:.6e}")

print(f"r^2 = {r2:.6f}")

T_cont = np.linspace(20, 520, 100)

X_cont = T_cont - 20

ln_alpha_pred = a1 * X_cont + A

plt.scatter(T, ln_alpha, color='red', label="Original Data", marker='o')

plt.plot(T_cont, ln_alpha_pred, color='blue', label="Regression Line")

plt.xlabel("Temperature (°C)")

plt.ylabel("ln(alpha)")

plt.title("Exponential Fit: ln(alpha) vs. Temperature")

plt.legend()

plt.grid()

plt.show()
Output

b)
Pseudo code:

Function RombergIntegration(f, a, b, n):

Step 1: Initialize Romberg Table

Create a table R of size (n+1) x (n+1)

Step 2: Compute Trapezoidal Rule for R[0][0]

For i = 0 to n:

h = (b - a) / (2^i)
sum = 0

For k = 1 to 2^(i-1):

sum += f(a + (2*k - 1) * h)

End For

If i == 0:

R[i][0] = (h / 2) * (f(a) + f(b)) # First trapezoidal step

Else:

R[i][0] = (1/2) * (R[i-1][0] + h * sum) # Recursive Trapezoidal


update

End If

End For

Step 3: Compute Higher-Order Approximations

For j = 1 to n:

For i = j to n:

R[i][j] = (4^j * R[i][j-1] - R[i-1][j-1]) / (4^j - 1) # Richardson


extrapolation

End For

End For

Step 4: Return the best estimate

Return R[n][n]
Code for part b

import numpy as np

import matplotlib.pyplot as plt

a0 = 1.105e-5

a1 = 0.0002

E = 210e3

L0 = 0.1

Ta = 20 # Lower limit

Tb = 520 # Upper limit

def alpha_func(T):

return a0 * np.exp(a1 * (T - 20))

def romberg_integral(f, a, b, n):

R = np.zeros((n, n))

h=b-a

R[0, 0] = (h / 2) * (f(a) + f(b))

for i in range(1, n):

h /= 2
sum_f = sum(f(a + k * h) for k in range(1, 2**i, 2))

R[i, 0] = 0.5 * R[i-1, 0] + h * sum_f

for j in range(1, i+1):

R[i, j] = (4**j * R[i, j-1] - R[i-1, j-1]) / (4**j - 1)

return R

n=5

R = romberg_integral(alpha_func, Ta, Tb, n)

I = R[n-1, n-1]

sigma = E * L0 * I

print("Romberg Integration Table:")

print(R)

print(f"Estimated Integral Value: {I:.6e}")

print(f"Stress in the steel bar: {sigma:.6f} MPa")

errors = np.abs(R[:, 0] - R[n-1, n-1])

plt.figure()

plt.semilogy(range(1, n+1), errors, 'o-', linewidth=2)

plt.xlabel('Iteration')
plt.ylabel('Error')

plt.title('Convergence of Romberg Integration')

plt.grid(True)

plt.show()

Output
Ques 2:

Soln:

import numpy as np

import matplotlib.pyplot as plt

def compute_F(X):

c0, c1, x0, x1 = X

F = np.zeros(4)

F[0] = c0 + c1 - 2 # Integral of 1 over [-1,1]

F[1] = c0 * x0 + c1 * x1 # Integral of x over [-1,1]

F[2] = c0 * x0**2 + c1 * x1**2 - 2/3 # Integral of x^2 over [-1,1]

F[3] = c0 * x0**3 + c1 * x1**3 # Integral of x^3 over [-1,1]

return F

def compute_Jacobian(X):

c0, c1, x0, x1 = X

J = np.zeros((4, 4))

J[0, :] = [1, 1, 0, 0]

J[1, :] = [x0, x1, c0, c1]

J[2, :] = [x0**2, x1**2, 2*c0*x0, 2*c1*x1]

J[3, :] = [x0**3, x1**3, 3*c0*x0**2, 3*c1*x1**2]

return J
def gauss_elimination(A, b):

n = len(b)

scale = np.max(np.abs(A), axis=1)

for k in range(n-1):

max_index = np.argmax(np.abs(A[k:n, k]) / scale[k:n]) + k

if max_index != k:

A[[k, max_index], :] = A[[max_index, k], :]

b[[k, max_index]] = b[[max_index, k]]

scale[[k, max_index]] = scale[[max_index, k]]

for i in range(k+1, n):

factor = A[i, k] / A[k, k]

A[i, k:] -= factor * A[k, k:]

b[i] -= factor * b[k]

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

def q2h2():

tol = 1e-6

max_iter = 100

X = np.array([1.0, 1.0, -0.5, 0.5])

for iter in range(1, max_iter + 1):


F = compute_F(X)

if np.linalg.norm(F, 2) < tol:

print(f'Convergence achieved after {iter} iterations.')

break

J = compute_Jacobian(X)

delta = gauss_elimination(J.copy(), -F)

X += delta

c0, c1, x0, x1 = X

print(f'Solution:\nc0 = {c0:.6f}\nc1 = {c1:.6f}\nx0 = {x0:.6f}\nx1 = {x1:.6f}')

nodes = [x0, x1]

weights = [c0, c1]

plt.figure()

plt.stem(nodes, weights, basefmt=" ")

plt.xlabel('x')

plt.ylabel('Weight')

plt.title('Two-Point Gauss-Legendre Nodes and Weights')

plt.xlim([-1, 1])

plt.ylim([0, max(weights) * 1.2])

plt.grid()

plt.show()

if __name__ == "__main__":

q2h2()
output:
Ques 3.

Soln.
import numpy as np

A = np.array([

[4, 0, -1, 0, 0],

[-2, 1, -2, 0, -3],

[0, 0, 3, -3, 0],

[0, -1, 0, 7, -6],

[-2, 0, 0, 0, 9]

], dtype=float)

B = np.array([15, 0, 7, 0, 0], dtype=float)

n = len(B)

L = np.zeros((n, n))

U = np.eye(n)

for j in range(n):

for i in range(j, n):

L[i, j] = A[i, j] - np.dot(L[i, :j], U[:j, j])

for i in range(j+1, n):

U[j, i] = (A[j, i] - np.dot(L[j, :j], U[:j, i])) / L[j, j]


# Forward substitution: Solve LY = B

Y = np.zeros(n)

for i in range(n):

Y[i] = (B[i] - np.dot(L[i, :i], Y[:i])) / L[i, i]

# Backward substitution: Solve UX = Y

X = np.zeros(n)

for i in range(n-1, -1, -1):

X[i] = (Y[i] - np.dot(U[i, i+1:], X[i+1:])) / U[i, i]

print("Concentrations of reactors (c1 to c5):")

print(X)

Output:

You might also like