The document provides Python code implementations for various numerical methods used in engineering analysis, including Taylor Series, Fixed Point Iteration, Bisection Method, Newton-Raphson Method, Secant Method, Multi-variable Newton's Method, Gauss-Naïve Elimination, Gauss-Seidel Iterative Method, Power Method for Eigenvalues, Linear Spline Interpolation, and Newton's Interpolation. Each method includes function definitions, user inputs for parameters, and output results. Additionally, some methods include graphical representations using matplotlib.
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 ratings0% found this document useful (0 votes)
3 views
EAlab Codes
The document provides Python code implementations for various numerical methods used in engineering analysis, including Taylor Series, Fixed Point Iteration, Bisection Method, Newton-Raphson Method, Secant Method, Multi-variable Newton's Method, Gauss-Naïve Elimination, Gauss-Seidel Iterative Method, Power Method for Eigenvalues, Linear Spline Interpolation, and Newton's Interpolation. Each method includes function definitions, user inputs for parameters, and output results. Additionally, some methods include graphical representations using matplotlib.
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/ 6
Python Codes for Numerical Methods: Engineering Analysis (18 ME 109)
1. Taylor Series for 𝒆𝒙
from math import* ##Taylor Series expansion for e^x x=float(input('Enter the value of x')) n=int(input('Enter the value of n')) sum=1 for i in range(1,n+1): sum=sum+(x**i)/factorial(i) print(sum)
2. Fixed point iteration: f(x)= 𝒆−𝒙 − 𝒙
from math import* import matplotlib.pyplot as plt import numpy as np def fixedpointitr(f, g, x0, tol): if f(x0)==tol: return x0 e=1 while(e > tol): x = g(x0) x0 = x e = abs(f(x0)) if e < tol: break return x0 ## Define the functions and the initial input g = lambda x : e**(-x) f = lambda x : e**(-x) - x x0 = float(input('Initial guess=')) tol= float(input('Tolerance=')) print("x0 = {} & f(x0)={}".format(x0,f(x0))) ## Pass the f(x) into Fixed Point Iteration method ans = fixedpointitr(f, g, x0, tol) print("The root of the equation: x = {} & f(x)={}".format(ans,f(ans))) #Plot the root x = np.linspace(ans-1, ans+1, 100) plt.plot(x,f(x)) plt.xlabel('x') plt.ylabel('f(x)') plt.title('Fixed Point Iteration') plt.scatter(ans,0,s=40,c='orange') plt.text(ans,0,'Root={}'.format(ans)) plt.grid() plt.show() 3. Bisection Method: f(x)= 𝒙𝟐 − 𝒙 − 𝟏 from math import* import matplotlib.pyplot as plt import numpy as np def bisection(f, xl, xu, tol): a = xl b = xu fa=f(a) fb=f(b) if fa*fb > 0: print("bad interval") return None e=1 while(e > tol): c=(a+b)/2 ##c=xr fc = f(c) e = abs(fc) if e==tol: break if fa*fc < 0: b=c fb=fc ## b, f(b) = c, f(c) if fb*fc < 0: a, fa = c, fc return c ## Define the function and the initial inputs f = lambda x: x**2 - x - 1 xl = int(input('Lower limit=')) xu = int(input('Upper limit=')) tol= float(input('Tolerance=')) ## Pass the f(x) into Newton Raphson method ans = bisection(f, xl, xu, tol) print("The root of the equation: x = {} & f(x)={}".format(ans,f(ans)))
4. Newton-Raphson method: : f(x)= 𝒙𝟐 − 𝒙 − 𝟏
from math import* ## Function for Newton Raphson method def NewtonRaphson(f, g, x0, tol): if f(x0)==tol: return x0 e=1 while e > tol: x0 = x0 - f(x0)/g(x0) e = abs(f(x0)) if e < tol: break return x0 ## Define the function, derivative and the initial input ## f = lambda x : e**(-x) - x ##g = lambda x : -1*e**(-x) - 1 f = lambda x : x**2 - x - 1 g = lambda x : 2*x - 1 x0 = float(input('Initial guess=')) tol= float(input('Tolerance=')) ## Pass the f(x) into Newton Raphson method ans = NewtonRaphson(f, g, x0, tol) print("The root of the equation: x = {} & f(x)={}".format(ans,f(ans)))
5. Secant Method: f(x)= 𝒆−𝒙 − 𝒙
from math import* ## Function for Secant method def Secant(f, x0, x1, tol): e=1 while e > tol: x1 = x1 - (f(x1)*(x0 - x1))/(f(x0)-f(x1)) e = abs(f(x1)) if e < tol: break return x1 ## Define the function, derivative and the initial input f = lambda x : e**(-x) - x x0 = float(input('Initial guess x0=')) x1 = float(input('Initial guess x1=')) tol= float(input('Tolerance=')) ## Pass the f(x) into Secant method ans = Secant(f, x0, x1, tol) print("The root of the equation: x = {} & f(x)={}".format(ans,f(ans)))
from math import* import matplotlib.pyplot as plt import numpy as np ## Newton Raphson method for non-linear multivariable function def MultiNewton(x0, y0, tol): if (u(x0,y0)==tol and v(x0,y0)==tol): return x0,y0 e1,e2 = 1,1 while (e1 > tol and e2 > tol): x0 = x0 - (u(x0,y0)*Dervy(x0,y0)-v(x0,y0)*Deruy(x0,y0))/(DetJ(x0,y0)) y0 = y0 - (v(x0,y0)*Derux(x0,y0)-u(x0,y0)*Dervx(x0,y0))/(DetJ(x0,y0)) e1,e2 = abs(u(x0,y0)),abs(v(x0,y0)) return x0,y0 ## Define the function, Jacobian and the initial input u = lambda x,y : x**2 + x*y - 10 v = lambda x,y : y + 3*x*(y**2) - 57 Derux = lambda x,y : 2*x+y Deruy = lambda x,y : x Dervx = lambda x,y : 3*(y**2) Dervy = lambda x,y : 1+6*x*y DetJ = lambda x,y : ((2*x+y)*(1+6*x*y))-(x*(3*(y**2))) x0 = float(input('Initial guess x0=')) y0 = float(input('Initial guess y0=')) tol= float(input('Tolerance=')) print("(x0,y0) = ({},{}) & u(x0,y0)={},v(x0,y0)={}:".format(x0,y0,u(x0,y0),v(x0,y0)))
7. Gauss-Naïve Elimination method:
from numpy import* A = array([[3,-0.1,-0.2],[0.1,7,-0.3],[0.3,-0.2,10]],float) b = array([7.85,-19.3,71.4],float) x = zeros(len(A)) print(A) print(b) col = len(A) row = len(A) for j in range (0,col-1): for i in range (j+1,row): if A[j,j] == 0: print('A{0}{0}=0'.format((j),(j))) break else: b[i] = b[i] - A[i,j]/A[j,j]*b[j] ## Forward elimination A[i,:] = A[i,:] - A[i,j]/A[j,j]*A[j,:] x[col-1] = b[col-1]/A[col-1,col-1] ## Back Substitution for i in range(col-2,-1,-1): x[i] = (b[i] - dot(A[i,i:],x[i:]))/A[i,i] print('The solution of the system is:') ##print(A) ##print(b) print(x)
8. Gauss-Seidel Iterative method:
f1 = lambda x,y,z: (1/3)*(7.85 + 0.1*y + 0.2*z) f2 = lambda x,y,z: (1/7)*(-19.3 - 0.1*x + 0.3*z) f3 = lambda x,y,z: (1/10)*(71.4 - 0.3*x + 0.2*y) x0 = 0 y0 = 0 z0 = 0 tol = 1 while tol>0.001: x1 = f1(x0,y0,z0) y1 = f2(x1,y0,z0) z1 = f3(x1,y1,z0) tol = abs(x0-x1) x0 = x1 y0 = y1 z0 = z1 print("The root of the equation: x = {} , y={} & x={}".format(x1,y1,z1)) print('\nSolution: x=%0.2f, y=%0.4f and z = %0.3f\n'%(x1,y1,z1))
9. Power method to find largest Eigenvalue and Eigenvector:
from math import* from numpy import* A = array([[3.556,-1.778,0],[-1.778,3.556,-1.778],[0,-1.778,3.556]],float) X0 = array([1,1,1]) for i in range(10): X1 = dot(A,X0) lmda = max(abs(X1)) X0 = X1/lmda print('The Eigenvalue:lambda = {}'.format(lmda)) print('The Eigenvector: X = {}'.format(X0))
10. Linear spline interpolation:
from numpy import* import matplotlib.pyplot as plt x = array([3, 4.5, 7, 9]) y = array([2.5, 1, 2.5, 0.5]) x_ip = float(input('Enter the value of x:')) smlx = nonzero(x < x_ip) x0 = max(x[smlx]) loc = where(x==x0) print(loc) i = loc[0] if (x_ip < min(x) or x_ip > max(x)): print('x value is out of the interpolation range.') else: y_ip = y[i] + ((y[i+1] - y[i])*(x_ip - x[i]))/(x[i+1] - x[i]) print(y_ip) ##plot the interpolated value plt.plot(x, y, "-o") plt.xlabel('x') plt.ylabel('ln(x)') plt.title('Linear Spine Interpolaton') plt.scatter(x_ip,y_ip,s=40,c='red') plt.text(x_ip,y_ip,'y_ip={}'.format(y_ip)) plt.grid() plt.show()
11. Newton,s interpolation:
from numpy import* import matplotlib.pyplot as plt x = array([-5, -1, 0, 2]) y = array([-2, 6, 1, 3]) m = len(y) coef = zeros([m, m]) # Matrix of devided differences # the first column is y coef[:,0] = y for j in range(1,m): for i in range(m-j): coef[i][j] = (coef[i+1][j-1] - coef[i][j-1]) / (x[i+j]-x[i]) print(coef) def newton_poly(coef, x_data, x): n = len(x_data) - 1 p = coef[n] for k in range(1,n+1): p = coef[n-k] + (x - x_data[n-k])*p return p x_new = arange(-5, 2.01, 1) y_new = newton_poly(coef[0,:], x, x_new) plt.plot(x, y, 'bo') plt.plot(x_new, y_new) x_ip = float(input('Enter the value of x:')) y_ip = newton_poly(coef[0,:], x, x_ip) print(y_ip) plt.scatter(x_ip,y_ip,s=40,c='red') plt.show()