├── 1D_Compressible_Flow.m ├── 2D_Diffusion_ADI.py ├── 2D_Diffusion_FTCS_1.py ├── 2D_Diffusion_FTCS_2.py ├── 2D_Navier_Stokes_Interrupted_1.cpp ├── 2D_Navier_Stokes_Interrupted_2.cpp ├── 2D_Navier_Stokes_Interrupted_3.cpp ├── 2D_Navier_Stokes_Outlines.m ├── 2D_Poisson_1.py ├── 2D_Poisson_2.py ├── 2D_Poisson_3.py ├── CNNs.py ├── CSR_by_AK.cpp ├── GMRES.cpp ├── Gauss_Seidel_Buggy_Code.cpp ├── Gauss_Seidel_Correct_Code.cpp ├── Gauss_Seidel_Debugged_by_ChatGPT.cpp ├── Max_Eigenvalue_Created_by_AK.cpp ├── Max_Eigenvalue_Parallel.cpp ├── Max_Eigenvalue_by_ChatGPT.cpp ├── Mesh.cpp ├── PINN.py ├── README.md ├── SOR_C_language.c ├── SOR_Cplus_language.cpp ├── SOR_Julia_language.jl ├── SOR_MATLAB_language.m ├── SOR_Python_language.py ├── Thomas_Incomplete_Code.cpp ├── image.png └── secant.py /1D_Compressible_Flow.m: -------------------------------------------------------------------------------- 1 | % Parameters 2 | gamma = 1.4; % Ratio of specific heats 3 | N = 1000; % Number of grid points 4 | L = 1; % Length of the domain 5 | dx = L/N; % Grid spacing 6 | dt = 0.0001; % Time step 7 | t_final = 0.2; % Final time 8 | 9 | % Initial conditions 10 | x = linspace(0, L, N); 11 | rho = ones(1, N); 12 | rho(x>0.5) = 0.125; 13 | u = zeros(1, N); 14 | p = ones(1, N); 15 | p(x>0.5) = 0.1; 16 | E = p/(gamma-1) + 0.5*rho.*u.^2; 17 | 18 | % Godunov method 19 | t = 0; 20 | while t < t_final 21 | % Compute time step 22 | a = sqrt(gamma*p./rho); 23 | dt = 0.25*dx./(abs(u) + a); 24 | dt = min(dt); 25 | if t + dt > t_final 26 | dt = t_final - t; 27 | end 28 | 29 | % Compute fluxes 30 | f = zeros(3, N+1); 31 | for i = 1:N+1 32 | if i == 1 33 | f(:, i) = euler_flux(rho(1), u(1), p(1), gamma); 34 | elseif i == N+1 35 | f(:, i) = euler_flux(rho(end), u(end), p(end), gamma); 36 | else 37 | f(:, i) = riemann_solver(rho(i-1), u(i-1), p(i-1), rho(i), u(i), p(i), gamma); 38 | end 39 | end 40 | 41 | % Update solution 42 | rho = rho - dt/dx*(f(1, 2:end) - f(1, 1:end-1)); 43 | u = u - dt/dx*(f(2, 2:end) - f(2, 1:end-1)); 44 | E = E - dt/dx*(f(3, 2:end) - f(3, 1:end-1)); 45 | p = (gamma-1)*(E - 0.5*rho.*u.^2); 46 | 47 | % Boundary conditions 48 | rho(1) = rho(2); 49 | rho(end) = rho(end-1); 50 | u(1) = -u(2); 51 | u(end) = -u(end-1); 52 | 53 | % Update time 54 | t = t + dt; 55 | end 56 | 57 | % Plot solution 58 | figure; 59 | plot(x, rho, 'b', 'LineWidth', 2); 60 | xlabel('x'); 61 | ylabel('Density'); 62 | title('1D Compressible Euler Equations with a Shock Wave'); 63 | xlim([0 L]); 64 | 65 | figure; 66 | plot(x, u, 'b', 'LineWidth', 2); 67 | xlabel('x'); 68 | ylabel('Velocity'); 69 | title('1D Compressible Euler Equations with a Shock Wave'); 70 | xlim([0 L]); 71 | 72 | figure; 73 | plot(x, p, 'b', 'LineWidth', 2); 74 | xlabel('x'); 75 | ylabel('Pressure'); 76 | title('1D Compressible Euler Equations with a Shock Wave'); 77 | xlim([0 L]); 78 | 79 | % Function to compute Euler fluxes 80 | function f = euler_flux(rho, u, p, gamma) 81 | f = [rho*u; rho*u^2 + p; (p/(gamma-1) + 0.5*rho*u^2 + p)*u]; 82 | end 83 | 84 | % Function to compute Riemann fluxes 85 | function f = riemann_solver(rho_l, u_l, p_l, rho_r, u_r, p_r, gamma) 86 | % Compute left and right state variables 87 | c_l = sqrt(gamma*p_l/rho_l); 88 | c_r = sqrt(gamma*p_r/rho_r); 89 | rho_star = 0.5*(rho_l + rho_r) + 0.5*(u_l - u_r)/c_l/sqrt(2/gamma/(gamma-1)/rho_l + 2/gamma/(gamma-1)/rho_r); 90 | p_star = 0.5*(p_l + p_r) + 0.5*(u_l - u_r)*rho_star*c_l; 91 | if p_star < 0 92 | p_star = 0; 93 | end 94 | u_star = 0.5*(u_l + u_r) + 0.5*(p_l - p_r)/rho_star/c_l; 95 | 96 | % Compute left and right wave speeds 97 | s_l = u_star - c_l; 98 | s_r = u_star + c_r; 99 | 100 | % Compute Euler fluxes at left and right states 101 | f_l = euler_flux(rho_l, u_l, p_l, gamma); 102 | f_r = euler_flux(rho_r, u_r, p_r, gamma); 103 | 104 | % Compute total energy per unit volume at the right state 105 | E_r = p_r/(gamma-1) + 0.5*rho_r*u_r^2; 106 | E_l = p_l/(gamma-1) + 0.5*rho_l*u_l^2; 107 | 108 | % Compute numerical flux 109 | if s_l > 0 110 | f = euler_flux(rho_l, u_l, p_l, gamma); 111 | elseif s_r < 0 112 | f = euler_flux(rho_r, u_r, p_r, gamma); 113 | else 114 | f = zeros(3, 1); 115 | f(1) = (s_r*f_l(1) - s_l*f_r(1) + s_l*s_r*(rho_r - rho_l))/(s_r - s_l); 116 | f(2) = (s_r*f_l(2) - s_l*f_r(2) + s_l*s_r*(rho_r*u_r - rho_l*u_l))/(s_r - s_l) + (p_star - 0.5*(rho_l + rho_r)*(s_r - s_l))*0.5*(sign(s_l) + sign(s_r)); 117 | f(3) = (s_r*f_l(3) - s_l*f_r(3) + s_l*s_r*(rho_r*E_r - rho_l*E_l))/(s_r - s_l) + (p_star*u_star - 0.5*(rho_l*u_l + rho_r*u_r)*(s_r - s_l))*0.5*(sign(s_l) + sign(s_r)); 118 | end 119 | end 120 | -------------------------------------------------------------------------------- /2D_Diffusion_ADI.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | # Define grid parameters 5 | Lx = 1.0 # length of domain in x direction 6 | Ly = 1.0 # length of domain in y direction 7 | Nx = 101 # number of grid points in x direction 8 | Ny = 101 # number of grid points in y direction 9 | dx = Lx/(Nx-1) # grid spacing in x direction 10 | dy = Ly/(Ny-1) # grid spacing in y direction 11 | x = np.linspace(0, Lx, Nx) 12 | y = np.linspace(0, Ly, Ny) 13 | X, Y = np.meshgrid(x, y) 14 | 15 | # Define time parameters 16 | T = 0.1 # total simulation time 17 | dt = 0.0001 # time step 18 | nt = int(T/dt) # number of time steps 19 | 20 | # Define diffusion coefficient and initial condition 21 | D = 0.1 # diffusion coefficient 22 | u0 = np.exp(-((X-0.5)**2 + (Y-0.5)**2)/0.01) 23 | 24 | # Define BTCS matrix 25 | alpha = D*dt/dx**2 26 | beta = D*dt/dy**2 27 | A = np.zeros((Nx*Ny, Nx*Ny)) 28 | for i in range(1, Nx-1): 29 | for j in range(1, Ny-1): 30 | k = i*Ny + j 31 | A[k,k] = 1 + 2*alpha + 2*beta 32 | A[k,k-1] = -alpha 33 | A[k,k+1] = -alpha 34 | A[k,k-Ny] = -beta 35 | A[k,k+Ny] = -beta 36 | A = np.linalg.inv(A) 37 | 38 | # Initialize solution array 39 | u = u0.flatten() 40 | 41 | # Time stepping loop 42 | for n in range(nt): 43 | un = u.copy() 44 | for i in range(1, Nx-1): 45 | for j in range(1, Ny-1): 46 | k = i*Ny + j 47 | u[k] = A[k,:] @ un 48 | # Apply zero-flux boundary conditions 49 | u[:Ny] = u[Ny:2*Ny] 50 | u[-Ny:] = u[-2*Ny:-Ny] 51 | u[::Ny] = u[Ny:Ny*(Nx-1):Ny] 52 | u[Ny*(Nx-1)::Ny] = u[Ny*(Nx-2):-Ny:Ny] 53 | 54 | # Reshape solution array to match grid and plot 55 | u = u.reshape((Nx, Ny)).T 56 | plt.contourf(x, y, u, levels=np.linspace(u.min(), u.max(), 101)) 57 | plt.colorbar() 58 | plt.xlabel('x') 59 | plt.ylabel('y') 60 | plt.title('Solution to 2D Diffusion Equation') 61 | plt.show() 62 | -------------------------------------------------------------------------------- /2D_Diffusion_FTCS_1.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | # Define the parameters 5 | D = 0.1 # Diffusion coefficient 6 | L = 1.0 # Length of the square box 7 | N = 100 # Number of grid points in each direction 8 | dx = L / (N - 1) # Grid spacing 9 | dy = L / (N - 1) 10 | dt = 0.0001 # Time step 11 | t_final = 1.0 # Final time 12 | 13 | # Define the initial condition 14 | u = np.zeros((N, N)) 15 | u[:, 0] = 1.0 # Bottom boundary 16 | u[:, -1] = 1.0 # Top boundary 17 | u[0, :] = 0.0 # Left boundary 18 | u[-1, :] = 0.0 # Right boundary 19 | 20 | # Define the coefficients for the FTCS method 21 | alpha = D * dt / dx**2 22 | beta = D * dt / dy**2 23 | 24 | # Iterate in time 25 | t = 0.0 26 | while t < t_final: 27 | # Compute the next time step 28 | u[1:-1, 1:-1] += alpha * (u[2:, 1:-1] - 2*u[1:-1, 1:-1] + u[:-2, 1:-1]) + beta * (u[1:-1, 2:] - 2*u[1:-1, 1:-1] + u[1:-1, :-2]) 29 | 30 | # Update the boundary conditions 31 | u[:, 0] = 1.0 # Bottom boundary 32 | u[:, -1] = 1.0 # Top boundary 33 | u[0, :] = 0.0 # Left boundary 34 | u[-1, :] = 0.0 # Right boundary 35 | 36 | # Increase the time 37 | t += dt 38 | 39 | # Plot the solution 40 | x = np.linspace(0, L, N) 41 | y = np.linspace(0, L, N) 42 | X, Y = np.meshgrid(x, y) 43 | plt.pcolormesh(X, Y, u, cmap='coolwarm') 44 | plt.colorbar() 45 | plt.xlabel('x') 46 | plt.ylabel('y') 47 | plt.title('Diffusion equation in a square box') 48 | plt.show() 49 | -------------------------------------------------------------------------------- /2D_Diffusion_FTCS_2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | # Define the parameters 5 | D = 1.0 # diffusion coefficient 6 | L = 1.0 # size of the square box 7 | Nx = 51 # number of grid points in the x direction 8 | Ny = 51 # number of grid points in the y direction 9 | dx = L/(Nx-1) # grid spacing in the x direction 10 | dy = L/(Ny-1) # grid spacing in the y direction 11 | dt = 0.0001 # time step 12 | T = 1.0 # final time 13 | 14 | # Define the initial conditions 15 | u = np.zeros((Nx,Ny)) 16 | u[:,0] = 1.0 # Dirichlet boundary condition at the bottom 17 | u[:,-1] = 1.0 # Dirichlet boundary condition at the top 18 | u[0,:] = 0.0 # Dirichlet boundary condition on the left 19 | u[-1,:] = 0.0 # Dirichlet boundary condition on the right 20 | 21 | # Define the FTCS scheme 22 | def ftcs(u, D, dx, dy, dt): 23 | Nx, Ny = u.shape 24 | u_new = u.copy() 25 | for i in range(1, Nx-1): 26 | for j in range(1, Ny-1): 27 | u_new[i,j] = u[i,j] + D*dt*(u[i+1,j] - 2*u[i,j] + u[i-1,j])/dx**2 \ 28 | + D*dt*(u[i,j+1] - 2*u[i,j] + u[i,j-1])/dy**2 29 | return u_new 30 | 31 | # Solve the diffusion equation using the FTCS scheme 32 | t = 0.0 33 | while t < T: 34 | u = ftcs(u, D, dx, dy, dt) 35 | t += dt 36 | 37 | # Plot the results 38 | x = np.linspace(0, L, Nx) 39 | y = np.linspace(0, L, Ny) 40 | X, Y = np.meshgrid(x, y) 41 | plt.contourf(X, Y, u, cmap='coolwarm') 42 | plt.colorbar() 43 | plt.xlabel('x') 44 | plt.ylabel('y') 45 | plt.title('Diffusion in a Square Box') 46 | plt.show() 47 | -------------------------------------------------------------------------------- /2D_Navier_Stokes_Interrupted_1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | const int Nx = 64; // Number of grid points in x-direction 7 | const int Ny = 64; // Number of grid points in y-direction 8 | const double Lx = 2.0 * M_PI; // Domain size in x-direction 9 | const double Ly = 2.0 * M_PI; // Domain size in y-direction 10 | const double dx = Lx / (Nx - 1); // Grid spacing in x-direction 11 | const double dy = Ly / (Ny - 1); // Grid spacing in y-direction 12 | const double dt = 0.01; // Time step 13 | const double T = 10.0; // Total simulation time 14 | const double Re = 100.0; // Reynolds number 15 | const double nu = 1.0 / Re; // Kinematic viscosity 16 | const double rho = 1.0; // Density 17 | 18 | // Function to compute initial condition for velocity 19 | void initialize_velocity(double* u, double* v) 20 | { 21 | double x, y; 22 | for (int i = 0; i < Nx; i++) 23 | { 24 | for (int j = 0; j < Ny; j++) 25 | { 26 | x = i * dx; 27 | y = j * dy; 28 | u[i * Ny + j] = cos(x) * sin(y); 29 | v[i * Ny + j] = -sin(x) * cos(y); 30 | } 31 | } 32 | } 33 | 34 | // Function to solve the implicit system for intermediate velocity 35 | void implicit_solve(double* rhs_u, double* rhs_v, double* u_star, double* v_star) 36 | { 37 | double* a = new double[Nx * Ny]; 38 | double* b = new double[Nx * Ny]; 39 | double* c = new double[Nx * Ny]; 40 | double* d = new double[Nx * Ny]; 41 | double* e = new double[Nx * Ny]; 42 | double* f = new double[Nx * Ny]; 43 | double* g = new double[Nx * Ny]; 44 | 45 | double alpha, beta, gamma; 46 | 47 | // Solve for u_star 48 | for (int i = 1; i < Nx - 1; i++) 49 | { 50 | for (int j = 1; j < Ny - 1; j++) 51 | { 52 | alpha = 0.5 * nu / (dx * dx); 53 | beta = 0.5 * nu / (dy * dy); 54 | gamma = -rho / dt; 55 | 56 | a[i * Ny + j] = -alpha; 57 | b[i * Ny + j] = 1.0 + 2.0 * alpha + 2.0 * beta; 58 | c[i * Ny + j] = -alpha; 59 | d[i * Ny + j] = gamma - rhs_u[i * Ny + j]; 60 | } 61 | } 62 | 63 | // Set boundary conditions for u_star 64 | for (int j = 1; j < Ny - 1; j++) 65 | { 66 | a[j] = 0.0; 67 | b[j] = 1.0; 68 | c[(Nx - 2) * Ny + j] = 0.0; 69 | b[(Nx - 1) * Ny + j] = 1.0; 70 | } 71 | for (int i = 72 | -------------------------------------------------------------------------------- /2D_Navier_Stokes_Interrupted_2.cpp: -------------------------------------------------------------------------------- 1 | // Solve tridiagonal system for u_star 2 | for (int j = 1; j < Ny - 1; j++) 3 | { 4 | for (int i = 1; i < Nx - 1; i++) 5 | { 6 | e[i * Ny + j] = a[i * Ny + j] / b[(i - 1) * Ny + j]; 7 | f[i * Ny + j] = c[i * Ny + j] / b[(i + 1) * Ny + j]; 8 | g[i * Ny + j] = d[i * Ny + j] / b[i * Ny + j]; 9 | } 10 | for (int i = 2; i < Nx - 1; i++) 11 | { 12 | e[i * Ny + j] = e[i * Ny + j] * f[(i - 1) * Ny + j]; 13 | g[i * Ny + j] = g[i * Ny + j] - e[i * Ny + j] * g[(i - 1) * Ny + j]; 14 | } 15 | u_star[(Nx - 2) * Ny + j] = g[(Nx - 2) * Ny + j]; 16 | for (int i = Nx - 3; i >= 1; i--) 17 | { 18 | u_star[i * Ny + j] = g[i * Ny + j] - f[i * Ny + j] * u_star[(i + 1) * Ny + j]; 19 | } 20 | } 21 | 22 | // Solve for v_star 23 | for (int i = 1; i < Nx - 1; i++) 24 | { 25 | for (int j = 1; j < Ny - 1; j++) 26 | { 27 | alpha = 0.5 * nu / (dx * dx); 28 | beta = 0.5 * nu / (dy * dy); 29 | gamma = -rho / dt; 30 | 31 | a[i * Ny + j] = -beta; 32 | b[i * Ny + j] = 1.0 + 2.0 * alpha + 2.0 * beta; 33 | c[i * Ny + j] = -beta; 34 | d[i * Ny + j] = gamma - rhs_v[i * Ny + j]; 35 | } 36 | } 37 | 38 | // Set boundary conditions for v_star 39 | for (int i = 1; i < Nx - 1; i++) 40 | { 41 | a[i * Ny] = 0.0; 42 | b[i * Ny] = 1.0; 43 | c[i * Ny + (Ny - 2)] = 0.0; 44 | b[i * Ny + (Ny - 1)] = 1.0; 45 | } 46 | for (int j = 1; j < Ny - 1; j++) 47 | { 48 | a[j] = 0.0; 49 | b[j] = 1.0; 50 | c[(Nx - 2) * Ny + j] = 0.0; 51 | b[(Nx - 1) * Ny + j] = 1.0; 52 | } 53 | 54 | // Solve tridiagonal system for v_star 55 | for (int i = 1; i < Nx - 1; i++) 56 | { 57 | for (int j = 1; j < Ny - 1; j++) 58 | { 59 | e[i * Ny + j] = a[i * Ny + j] / b[i * Ny + (j - 1)]; 60 | f[i * Ny + j] = c[i * Ny + j] / b[i * Ny + (j + 1)]; 61 | -------------------------------------------------------------------------------- /2D_Navier_Stokes_Interrupted_3.cpp: -------------------------------------------------------------------------------- 1 | g[i * Ny + j] = d[i * Ny + j] / b[i * Ny + j]; 2 | } 3 | for (int j = 2; j < Ny - 1; j++) 4 | { 5 | e[i * Ny + j] = e[i * Ny + j] * f[i * Ny + (j - 1)]; 6 | g[i * Ny + j] = g[i * Ny + j] - e[i * Ny + j] * g[i * Ny + (j - 1)]; 7 | } 8 | v_star[i * Ny + (Ny - 2)] = g[i * Ny + (Ny - 2)]; 9 | for (int j = Ny - 3; j >= 1; j--) 10 | { 11 | v_star[i * Ny + j] = g[i * Ny + j] - f[i * Ny + j] * v_star[i * Ny + (j + 1)]; 12 | } 13 | } 14 | 15 | // Calculate u_n+1 and v_n+1 16 | for (int i = 1; i < Nx - 1; i++) 17 | { 18 | for (int j = 1; j < Ny - 1; j++) 19 | { 20 | u[i * Ny + j] = u_star[i * Ny + j] - dt / dx * (p[(i + 1) * Ny + j] - p[i * Ny + j]); 21 | v[i * Ny + j] = v_star[i * Ny + j] - dt / dy * (p[i * Ny + (j + 1)] - p[i * Ny + j]); 22 | } 23 | } 24 | 25 | // Apply periodic boundary conditions to u and v 26 | for (int i = 0; i < Nx; i++) 27 | { 28 | u[i * Ny] = u[i * Ny + (Ny - 2)]; 29 | u[i * Ny + (Ny - 1)] = u[i * Ny + 1]; 30 | v[i * Ny] = v[i * Ny + (Ny - 2)]; 31 | v[i * Ny + (Ny - 1)] = v[i * Ny + 1]; 32 | } 33 | for (int j = 0; j < Ny; j++) 34 | { 35 | u[j] = u[(Nx - 2) * Ny + j]; 36 | u[(Nx - 1) * Ny + j] = u[Ny + j]; 37 | v[j] = v[(Nx - 2) * Ny + j]; 38 | v[(Nx - 1) * Ny + j] = v[Ny + j]; 39 | } 40 | 41 | // Output results to file 42 | if (t % output_freq == 0) 43 | { 44 | std::ofstream file("output_" + std::to_string(t) + ".txt"); 45 | for (int j = 0; j < Ny; j++) 46 | { 47 | for (int i = 0; i < Nx; i++) 48 | { 49 | file << i * dx << " " << j * dy << " " << u[i * Ny + j] << " " << v[i * Ny + j] << "\n"; 50 | } 51 | file << "\n"; 52 | } 53 | file.close(); 54 | } 55 | } 56 | 57 | int main() 58 | { 59 | // Simulation parameters 60 | const int Nx = 64; // Number of grid points in the x-direction 61 | const int Ny = 64; // Number of grid points in the y-direction 62 | const double Lx = 2.0 * M_PI; // Length of the domain in the x-direction 63 | const double Ly = 64 | -------------------------------------------------------------------------------- /2D_Navier_Stokes_Outlines.m: -------------------------------------------------------------------------------- 1 | % Define the domain and discretization grid 2 | Lx = 2*pi; Ly = 2*pi; % Domain size 3 | Nx = 64; Ny = 64; % Number of grid points in x and y directions 4 | dx = Lx/Nx; dy = Ly/Ny; % Grid spacing 5 | x = linspace(0,Lx-dx,Nx); y = linspace(0,Ly-dy,Ny); 6 | [X,Y] = meshgrid(x,y); 7 | 8 | % Initialize velocity and pressure fields 9 | u = zeros(Ny,Nx); v = zeros(Ny,Nx); % Velocity components 10 | p = zeros(Ny,Nx); % Pressure 11 | 12 | % Define time step and simulation time 13 | dt = 0.01; % Time step 14 | T = 10; % Simulation time 15 | Nt = round(T/dt); % Number of time steps 16 | 17 | % Define boundary conditions 18 | u_exact = @(t,x,y) -cos(x).*sin(y).*exp(-2*t); % Exact solution for u 19 | v_exact = @(t,x,y) sin(x).*cos(y).*exp(-2*t); % Exact solution for v 20 | u(:,1) = u_exact(0,x,0); u(:,end) = u_exact(0,x,Ly); 21 | u(1,:) = u_exact(0,0,y); u(end,:) = u_exact(0,Lx,y); 22 | v(:,1) = v_exact(0,x,0); v(:,end) = v_exact(0,x,Ly); 23 | v(1,:) = v_exact(0,0,y); v(end,:) = v_exact(0,Lx,y); 24 | 25 | % Loop over time steps 26 | for n = 1:Nt 27 | % Solve for intermediate velocity using implicit time integration 28 | % Insert code here 29 | % ... 30 | 31 | % Solve for pressure using pressure projection scheme 32 | % Insert code here 33 | % ... 34 | 35 | % Correct velocity field with pressure 36 | % Insert code here 37 | % ... 38 | 39 | % Apply boundary conditions 40 | u(:,1) = u_exact(n*dt,x,0); u(:,end) = u_exact(n*dt,x,Ly); 41 | u(1,:) = u_exact(n*dt,0,y); u(end,:) = u_exact(n*dt,Lx,y); 42 | v(:,1) = v_exact(n*dt,x,0); v(:,end) = v_exact(n*dt,x,Ly); 43 | v(1,:) = v_exact(n*dt,0,y); v(end,:) = v_exact(n*dt,Lx,y); 44 | 45 | % Output results 46 | % Insert code here 47 | % ... 48 | end 49 | -------------------------------------------------------------------------------- /2D_Poisson_1.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | # Define the grid size and spacing 5 | N = 50 # Number of grid points in each direction 6 | L = 1.0 # Length of the square domain 7 | h = L / (N - 1) # Spacing between grid points 8 | 9 | # Define the boundary conditions and source term 10 | u_top = np.zeros(N) 11 | u_bottom = np.zeros(N) 12 | u_left = np.zeros(N) 13 | u_right = np.zeros(N) 14 | f = np.zeros((N, N)) 15 | f[N//2, N//2] = 1.0/h**2 16 | 17 | # Define the coefficient matrix and the right-hand side vector 18 | A = np.zeros((N*N, N*N)) 19 | b = np.zeros(N*N) 20 | 21 | for i in range(N): 22 | for j in range(N): 23 | k = i*N + j # Index of the unknown u_ij 24 | if i == 0: 25 | A[k, k] = 1.0 26 | b[k] = u_top[j] 27 | elif i == N-1: 28 | A[k, k] = 1.0 29 | b[k] = u_bottom[j] 30 | elif j == 0: 31 | A[k, k] = 1.0 32 | b[k] = u_left[i] 33 | elif j == N-1: 34 | A[k, k] = 1.0 35 | b[k] = u_right[i] 36 | else: 37 | A[k, k] = -4.0 38 | A[k, k-1] = 1.0 39 | A[k, k+1] = 1.0 40 | A[k, k-N] = 1.0 41 | A[k, k+N] = 1.0 42 | b[k] = f[i,j] 43 | 44 | # Solve the linear system 45 | u = np.linalg.solve(A, b) 46 | 47 | # Reshape the solution vector into a 2D array 48 | U = u.reshape((N, N)) 49 | 50 | # Plot the solution 51 | x = np.linspace(0, L, N) 52 | y = np.linspace(0, L, N) 53 | X, Y = np.meshgrid(x, y) 54 | plt.contourf(X, Y, U) 55 | plt.colorbar() 56 | plt.xlabel('x') 57 | plt.ylabel('y') 58 | plt.title('2D Poisson equation solution') 59 | plt.show() 60 | -------------------------------------------------------------------------------- /2D_Poisson_2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | # Define the grid size and spacing 5 | N = 50 # Number of grid points in each direction 6 | L = 1.0 # Length of the square domain 7 | h = L / (N - 1) # Spacing between grid points 8 | 9 | # Define the boundary conditions and source term 10 | u_top = np.zeros(N) 11 | u_bottom = np.zeros(N) 12 | u_left = np.zeros(N) 13 | u_right = np.zeros(N) 14 | x = np.linspace(0, L, N) 15 | y = np.linspace(0, L, N) 16 | X, Y = np.meshgrid(x, y) 17 | f = np.sin(X)*np.cos(Y) 18 | 19 | # Define the coefficient matrix and the right-hand side vector 20 | A = np.zeros((N*N, N*N)) 21 | b = np.zeros(N*N) 22 | 23 | for i in range(N): 24 | for j in range(N): 25 | k = i*N + j # Index of the unknown u_ij 26 | if i == 0: 27 | A[k, k] = 1.0 28 | b[k] = u_top[j] 29 | elif i == N-1: 30 | A[k, k] = 1.0 31 | b[k] = u_bottom[j] 32 | elif j == 0: 33 | A[k, k] = 1.0 34 | b[k] = u_left[i] 35 | elif j == N-1: 36 | A[k, k] = 1.0 37 | b[k] = u_right[i] 38 | else: 39 | A[k, k] = -4.0 40 | A[k, k-1] = 1.0 41 | A[k, k+1] = 1.0 42 | A[k, k-N] = 1.0 43 | A[k, k+N] = 1.0 44 | b[k] = f[i,j] 45 | 46 | # Solve the linear system 47 | u = np.linalg.solve(A, b) 48 | 49 | # Reshape the solution vector into a 2D array 50 | U = u.reshape((N, N)) 51 | 52 | # Plot the solution 53 | plt.contourf(X, Y, U) 54 | plt.colorbar() 55 | plt.xlabel('x') 56 | plt.ylabel('y') 57 | plt.title('2D Poisson equation solution with sin(x)*cos(y) source term') 58 | plt.show() 59 | -------------------------------------------------------------------------------- /2D_Poisson_3.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | 4 | # Define the grid size and spacing 5 | N = 100 # Number of grid points in each direction 6 | Lx = 5.0 # Length of the rectangular domain 7 | Ly = 3.0 # Width of the rectangular domain 8 | h = Lx / (N - 1) # Spacing between grid points 9 | 10 | # Define the boundary conditions and source term 11 | u_top = np.zeros(N) 12 | u_bottom = np.zeros(N) 13 | u_left = np.zeros(N) 14 | u_right = np.zeros(N) 15 | x = np.linspace(-Lx/2, Lx/2, N) 16 | y = np.linspace(-Ly/2, Ly/2, N) 17 | X, Y = np.meshgrid(x, y) 18 | f = np.sin(X)*np.cos(Y) 19 | 20 | # Define the coefficient matrix and the right-hand side vector 21 | A = np.zeros((N*N, N*N)) 22 | b = np.zeros(N*N) 23 | 24 | for i in range(N): 25 | for j in range(N): 26 | k = i*N + j # Index of the unknown u_ij 27 | if i == 0: 28 | A[k, k] = 1.0 29 | b[k] = u_top[j] 30 | elif i == N-1: 31 | A[k, k] = 1.0 32 | b[k] = u_bottom[j] 33 | elif j == 0: 34 | A[k, k] = 1.0 35 | b[k] = u_left[i] 36 | elif j == N-1: 37 | A[k, k] = 1.0 38 | b[k] = u_right[i] 39 | elif x[i] == -Lx/2 or x[i] == Lx/2: 40 | A[k, k] = 1.0 41 | b[k] = 0.0 42 | elif y[j] == -Ly/2 or y[j] == Ly/2: 43 | A[k, k] = -3.0 44 | if j == 1: 45 | A[k, k+N] = 1.0 46 | b[k] = 0.0 47 | elif j == N-2: 48 | A[k, k-N] = 1.0 49 | b[k] = 0.0 50 | else: 51 | A[k, k-1] = 1.0 52 | A[k, k+1] = 1.0 53 | b[k] = f[i,j] 54 | else: 55 | A[k, k] = -4.0 56 | A[k, k-1] = 1.0 57 | A[k, k+1] = 1.0 58 | A[k, k-N] = 1.0 59 | A[k, k+N] = 1.0 60 | b[k] = f[i,j] 61 | 62 | # Solve the linear system 63 | u = np.linalg.solve(A, b) 64 | 65 | # Reshape the solution vector into a 2D array 66 | U = u.reshape((N, N)) 67 | 68 | # Plot the solution 69 | plt.contourf(X, Y, U) 70 | plt.colorbar() 71 | plt.xlabel('x') 72 | plt.ylabel('y') 73 | plt.title('2D Poisson equation solution with sin(x)*cos(y) source term') 74 | plt.show() 75 | -------------------------------------------------------------------------------- /CNNs.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | from tensorflow.keras.models import Sequential 3 | from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout, Conv2DTranspose, UpSampling2D, BatchNormalization 4 | from tensorflow.keras.optimizers import Adam 5 | import numpy as np 6 | import os 7 | 8 | def load_data(path): 9 | # Load your dataset here 10 | pass 11 | 12 | def preprocess_data(data): 13 | # Preprocess your data here (normalize, resize, split) 14 | pass 15 | 16 | def create_model(input_shape): 17 | model = Sequential() 18 | 19 | # Encoder 20 | model.add(Conv2D(32, (3, 3), activation='relu', padding='same', input_shape=input_shape)) 21 | model.add(MaxPooling2D((2, 2), padding='same')) 22 | model.add(Conv2D(64, (3, 3), activation='relu', padding='same')) 23 | model.add(MaxPooling2D((2, 2), padding='same')) 24 | model.add(Conv2D(128, (3, 3), activation='relu', padding='same')) 25 | model.add(MaxPooling2D((2, 2), padding='same')) 26 | 27 | # Decoder 28 | model.add(Conv2DTranspose(128, (3, 3), activation='relu', padding='same')) 29 | model.add(UpSampling2D((2, 2))) 30 | model.add(Conv2DTranspose(64, (3, 3), activation='relu', padding='same')) 31 | model.add(UpSampling2D((2, 2))) 32 | model.add(Conv2DTranspose(32, (3, 3), activation='relu', padding='same')) 33 | model.add(UpSampling2D((2, 2))) 34 | model.add(Conv2DTranspose(3, (3, 3), activation='linear', padding='same')) # 3 channels for u, v velocity components and pressure 35 | 36 | return model 37 | 38 | def train_model(model, train_data, val_data, epochs, batch_size): 39 | model.compile(optimizer=Adam(learning_rate=0.001), 40 | loss='mse', 41 | metrics=['mae']) 42 | 43 | history = model.fit(train_data, 44 | epochs=epochs, 45 | batch_size=batch_size, 46 | validation_data=val_data) 47 | 48 | return history, model 49 | 50 | def test_model(model, test_data): 51 | # Evaluate the model on the test dataset 52 | pass 53 | 54 | if __name__ == '__main__': 55 | # Load and preprocess the data 56 | dataset_path = "path/to/your/dataset" 57 | data = load_data(dataset_path) 58 | train_data, val_data, test_data = preprocess_data(data) 59 | 60 | # Create the CNN model 61 | input_shape = (128, 128, 1) # Input shape based on your preprocessed data 62 | model = create_model(input_shape) 63 | 64 | # Train the model 65 | epochs = 50 66 | batch_size = 32 67 | history, trained_model = train_model(model, train_data, val_data, epochs, batch_size) 68 | 69 | # Test the model 70 | test_results = test_model(trained_model, test_data) 71 | -------------------------------------------------------------------------------- /CSR_by_AK.cpp: -------------------------------------------------------------------------------- 1 | #define _USE_MATH_DEFINES 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std ; 8 | 9 | void CSR(double **a , int n){ 10 | 11 | double *V_k_aa ; 12 | int *V_k_ai , *V_k_aj ; 13 | int V_k_non_zeros_elements ; 14 | V_k_non_zeros_elements = 0 ; 15 | 16 | for (int i = 0 ; i < n ; i ++){ 17 | for (int j = 0 ; j < n ; j++){ 18 | if(a[i][j] != 0.0 ){V_k_non_zeros_elements ++ ;} 19 | } 20 | } 21 | 22 | V_k_aa = new double[V_k_non_zeros_elements] ; 23 | V_k_ai = new int[V_k_non_zeros_elements] ; 24 | V_k_aj = new int[n + 1] ; 25 | V_k_aj[0] = 0 ; 26 | 27 | int alarm = 0 ; 28 | int counter = 0 ; 29 | 30 | for (int i = 0 ; i < n ; i ++){ 31 | for (int j = 0 ; j < n ; j ++){ 32 | 33 | if(a[i][j] != 0 ){ 34 | alarm ++ ; 35 | V_k_aa[counter] = a[i][j] ; 36 | if (alarm == 1) V_k_aj[i] = counter ; 37 | V_k_ai[counter] = j ; counter ++ ; 38 | } 39 | } 40 | alarm = 0 ; 41 | } 42 | 43 | V_k_aj[n] = V_k_non_zeros_elements ; 44 | 45 | //print the results 46 | cout << "Array of non zero elements:" << endl ; 47 | for(int i=0; i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | using namespace Eigen; 7 | 8 | int main() { 9 | // Define the size of the matrix 10 | const int N = 100; 11 | 12 | // Define the sparse matrix A 13 | SparseMatrix A(N, N); 14 | for (int i = 0; i < N; i++) { 15 | for (int j = 0; j < N; j++) { 16 | double val = 0.0; 17 | if (i == j) { 18 | val = 2.0; 19 | } 20 | else if (i == j-1 || i == j+1) { 21 | val = -1.0; 22 | } 23 | if (val != 0.0) { 24 | A.insert(i, j) = val; 25 | } 26 | } 27 | } 28 | A.makeCompressed(); 29 | 30 | // Define the right-hand side vector b 31 | VectorXd b(N); 32 | b.setOnes(); 33 | 34 | // Initialize the solution vector x 35 | VectorXd x(N); 36 | x.setZero(); 37 | 38 | // Solve the linear system using the GMRES algorithm 39 | int max_iterations = 1000; // Maximum number of iterations 40 | double tolerance = 1e-6; // Tolerance for the iterative solver 41 | BiCGSTAB> inner_solver; // Inner linear solver 42 | inner_solver.setTolerance(tolerance); // Set the tolerance for the inner solver 43 | GMRES> solver; // Outer linear solver 44 | solver.setMaxIterations(max_iterations); // Set the maximum number of iterations 45 | solver.setTolerance(tolerance); // Set the tolerance for the solver 46 | solver.compute(A); // Compute the preconditioner (identity matrix) 47 | x = solver.solveWithGuess(b, x, inner_solver); // Solve the linear system 48 | 49 | // Print the solution vector 50 | cout << "Solution vector x:" << endl; 51 | for (int i = 0; i < N; i++) { 52 | cout << x(i) << endl; 53 | } 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /Gauss_Seidel_Buggy_Code.cpp: -------------------------------------------------------------------------------- 1 | #define _USE_MATH_DEFINES 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std ; 8 | 9 | void GS(double **a, double x[], double b[], int n){ 10 | 11 | double *r = new double[n] ; 12 | double *xK = new double[n] ; 13 | 14 | for(int j = 0 ; j < n ; j++){r[j] = 0 ; xK[j] = 0; x[j] = 0;} 15 | 16 | while(true){ 17 | 18 | for(int i = 10 ; i < n ; i ++){ 19 | 20 | double sum1 = 0; 21 | double sum2 = 0; 22 | 23 | for(int j = 0 ; j < i ; j++){if(i==0){sum1 = 0 ; break ;} 24 | sum1 += a[i][j]*xK[j] ;} 25 | 26 | for(int j = i+1 ; j < n ; j++) 27 | sum2 += a[i][j]*x[j] ; 28 | 29 | xK[i] = (1./a[i][i])*(b[i] - sum1 - sum2); 30 | } 31 | 32 | for(int i = 0 ; i < n ; i ++){x[i] = xK[i];} 33 | 34 | for(int i = 0 ; i < n ; i ++){ 35 | 36 | double sum = 0 ; 37 | for(int k = 0 ; k < n ; k ++) 38 | sum += a[i][k]*x[k] ; 39 | 40 | r[i] = b[i] - sum ; 41 | } 42 | 43 | double max = 0 ; 44 | for(int i = 0 ; i < n ; i ++){if(abs(r[i]) > max){max = abs(r[i]);}} 45 | if(max < pow(10. , -6.)){break ;} 46 | } 47 | 48 | return ; 49 | } 50 | 51 | int main(){ 52 | 53 | // Formulate the problem as Ax = b 54 | 55 | int n = 5 ; 56 | double *b, *x ; 57 | b = new double[n] ; 58 | x = new double[n] ; 59 | 60 | double** a = new double*[n] ; 61 | for (int i = 0 ; i < n ; i++) 62 | a[i] = new double[n]; 63 | 64 | // As an example 65 | 66 | b[0] = 4. ; 67 | b[1] = 24. ; 68 | b[2] = 8. ; 69 | b[3] = 5. ; 70 | b[4] = 24. ; 71 | 72 | a[0][0]=6; a[0][1]=2; a[0][2]=3 ; a[0][3]=4 ; a[0][4]=1 ; 73 | a[1][0]=2 ; a[1][1]=6 ; a[1][2]=2 ; a[1][3]=3 ; a[1][4]=4 ; 74 | a[2][0]=3 ; a[2][1]=2 ; a[2][2]=6 ; a[2][3]=2 ; a[2][4]=3 ; 75 | a[3][0]=4 ; a[3][1]=3 ; a[3][2]=2 ; a[3][3]=6 ; a[3][4]=2 ; 76 | a[4][0]=1 ; a[4][1]=4 ; a[4][2]=3 ; a[4][3]=2 ; a[4][4]=6 ; 77 | 78 | GS(a, x, b, n) ; 79 | 80 | for(int i=0; i 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std ; 8 | 9 | void GS(double **a, double x[], double b[], int n){ 10 | 11 | double *r = new double[n] ; 12 | double *xK = new double[n] ; 13 | 14 | for(int j = 0 ; j < n ; j++){r[j] = 0 ; xK[j] = 0; x[j] = 0;} 15 | 16 | while(true){ 17 | 18 | for(int i = 0 ; i < n ; i ++){ 19 | 20 | double sum1 = 0; 21 | double sum2 = 0; 22 | 23 | for(int j = 0 ; j < i ; j++){if(i==0){sum1 = 0 ; break ;} 24 | sum1 += a[i][j]*xK[j] ;} 25 | 26 | for(int j = i+1 ; j < n ; j++) 27 | sum2 += a[i][j]*x[j] ; 28 | 29 | xK[i] = (1./a[i][i])*(b[i] - sum1 - sum2); 30 | } 31 | 32 | for(int i = 0 ; i < n ; i ++){x[i] = xK[i];} 33 | 34 | for(int i = 0 ; i < n ; i ++){ 35 | 36 | double sum = 0 ; 37 | for(int k = 0 ; k < n ; k ++) 38 | sum += a[i][k]*x[k] ; 39 | 40 | r[i] = b[i] - sum ; 41 | } 42 | 43 | double max = 0 ; 44 | for(int i = 0 ; i < n ; i ++){if(abs(r[i]) > max){max = abs(r[i]);}} 45 | if(max < pow(10. , -6.)){break ;} 46 | } 47 | 48 | return ; 49 | } 50 | 51 | int main(){ 52 | 53 | // Formulate the problem as Ax = b 54 | 55 | int n = 5 ; 56 | double *b, *x ; 57 | b = new double[n] ; 58 | x = new double[n] ; 59 | 60 | double** a = new double*[n] ; 61 | for (int i = 0 ; i < n ; i++) 62 | a[i] = new double[n]; 63 | 64 | // As an example 65 | 66 | b[0] = 4. ; 67 | b[1] = 24. ; 68 | b[2] = 8. ; 69 | b[3] = 5. ; 70 | b[4] = 24. ; 71 | 72 | a[0][0]=6; a[0][1]=2; a[0][2]=3 ; a[0][3]=4 ; a[0][4]=1 ; 73 | a[1][0]=2 ; a[1][1]=6 ; a[1][2]=2 ; a[1][3]=3 ; a[1][4]=4 ; 74 | a[2][0]=3 ; a[2][1]=2 ; a[2][2]=6 ; a[2][3]=2 ; a[2][4]=3 ; 75 | a[3][0]=4 ; a[3][1]=3 ; a[3][2]=2 ; a[3][3]=6 ; a[3][4]=2 ; 76 | a[4][0]=1 ; a[4][1]=4 ; a[4][2]=3 ; a[4][3]=2 ; a[4][4]=6 ; 77 | 78 | GS(a, x, b, n) ; 79 | 80 | for(int i=0; i 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | const double THRESHOLD = pow(10. , -6.); 10 | 11 | void GS(double **a, double x[], double b[], int n) { 12 | double *r = new double[n]; 13 | double *xK = new double[n]; 14 | for (int j = 0; j < n; j++) { 15 | r[j] = 0; 16 | xK[j] = 0; 17 | x[j] = 0; 18 | } 19 | while (true) { 20 | for (int i = 0; i < n; i++) { 21 | double sum1 = 0; 22 | double sum2 = 0; 23 | for (int j = 0; j < i; j++) { 24 | sum1 += a[i][j] * xK[j]; 25 | } 26 | for (int j = i + 1; j < n; j++) { 27 | sum2 += a[i][j] * x[j]; 28 | } 29 | xK[i] = (1. / a[i][i]) * (b[i] - sum1 - sum2); 30 | } 31 | for (int i = 0; i < n; i++) { 32 | x[i] = xK[i]; 33 | } 34 | for (int i = 0; i < n; i++) { 35 | double sum = 0; 36 | for (int k = 0; k < n; k++) { 37 | sum += a[i][k] * x[k]; 38 | } 39 | r[i] = b[i] - sum; 40 | } 41 | double max = 0; 42 | for (int i = 0; i < n; i++) { 43 | if (abs(r[i]) > max) { 44 | max = abs(r[i]); 45 | } 46 | } 47 | if (max < THRESHOLD) { 48 | break; 49 | } 50 | } 51 | delete[] r; 52 | delete[] xK; 53 | return; 54 | } 55 | 56 | void printSolution(double x[], int n) { 57 | for (int i = 0; i < n; i++) { 58 | cout << "x" << i << " " << x[i] << endl; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Max_Eigenvalue_Created_by_AK.cpp: -------------------------------------------------------------------------------- 1 | #define _USE_MATH_DEFINES 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std ; 8 | 9 | void MaxEval(double **a , int n){ 10 | 11 | double eval = 0 ; 12 | double *v = new double[n] ; 13 | double *q = new double[n] ; 14 | for(int i = 0 ; i < n ; i ++) 15 | q[i] = rand() ; 16 | 17 | double sum = 0 ; 18 | for(int i = 0 ; i < n ; i ++) 19 | sum += q[i]*q[i] ; 20 | 21 | for(int i = 0 ; i < n ; i ++) 22 | q[i] = q[i]/sqrt(sum) ; 23 | 24 | for(int k = 0 ; k < 100 ; k ++){ 25 | 26 | for(int i = 0 ; i < n ; i++){ 27 | double sum = 0 ; 28 | 29 | for(int j =0 ; j < n ; j++) 30 | sum += a[i][j]*q[j] ; 31 | v[i] = sum ; 32 | } 33 | 34 | double sum = 0 ; 35 | for(int i = 0 ; i < n ; i++) 36 | sum += v[i]*q[i] ; 37 | 38 | if(abs(sum-eval) < pow(10.,-6.)){cout << sum << endl ; break ;} 39 | 40 | eval = sum ; 41 | 42 | sum = 0 ; 43 | for(int i = 0 ; i < n ; i ++) 44 | sum += v[i]*v[i] ; 45 | 46 | for(int i = 0 ; i < n ; i ++) 47 | q[i] = v[i]/sqrt(sum) ; 48 | 49 | } 50 | return ; 51 | } 52 | 53 | int main(){ 54 | 55 | // For example, consider matrix A 56 | int n = 3 ; 57 | double** a = new double*[n] ; 58 | for (int i = 0 ; i < n ; i++) 59 | a[i] = new double[n]; 60 | 61 | // As an example, let's find the maximum eigenvalue of the following matrix 62 | a[0][0]=0; a[0][1]=-17; a[0][2]=21; 63 | a[1][0]=0; a[1][1]=13; a[1][2]=-15; 64 | a[2][0]=0; a[2][1]=10; a[2][2]=-12; 65 | 66 | MaxEval(a , n); 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Max_Eigenvalue_Parallel.cpp: -------------------------------------------------------------------------------- 1 | #define _USE_MATH_DEFINES 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | void MaxEval(double **a, int n){ 11 | 12 | double eval = 0; 13 | double *v = new double[n]; 14 | double *q = new double[n]; 15 | for(int i = 0; i < n; i++) 16 | q[i] = rand(); 17 | 18 | double sum = 0; 19 | for(int i = 0; i < n; i++) 20 | sum += q[i] * q[i]; 21 | 22 | for(int i = 0; i < n; i++) 23 | q[i] = q[i] / sqrt(sum); 24 | 25 | #pragma omp parallel 26 | { 27 | double* local_v = new double[n]; 28 | double* local_q = new double[n]; 29 | double local_sum = 0; 30 | int num_threads = omp_get_num_threads(); 31 | int thread_id = omp_get_thread_num(); 32 | 33 | for(int k = 0; k < 100; k++){ 34 | #pragma omp for 35 | for(int i = 0; i < n; i++){ 36 | double sum = 0; 37 | for(int j = 0; j < n; j++) 38 | sum += a[i][j] * q[j]; 39 | local_v[i] = sum; 40 | } 41 | 42 | #pragma omp barrier 43 | 44 | #pragma omp for reduction(+:local_sum) 45 | for(int i = 0; i < n; i++) 46 | local_sum += local_v[i] * q[i]; 47 | 48 | #pragma omp critical 49 | { 50 | eval += local_sum; 51 | } 52 | 53 | #pragma omp single 54 | { 55 | double diff = fabs(local_sum - eval); 56 | if(diff < pow(10., -6.)){ 57 | cout << eval << endl; 58 | break; 59 | } 60 | eval = local_sum; 61 | local_sum = 0; 62 | } 63 | 64 | #pragma omp barrier 65 | 66 | #pragma omp for reduction(+:local_sum) 67 | for(int i = 0; i < n; i++) 68 | local_sum += local_v[i] * local_v[i]; 69 | 70 | #pragma omp for 71 | for(int i = 0; i < n; i++) 72 | local_q[i] = local_v[i] / sqrt(local_sum); 73 | 74 | #pragma omp for 75 | for(int i = 0; i < n; i++) 76 | q[i] = local_q[i]; 77 | } 78 | 79 | delete[] local_v; 80 | delete[] local_q; 81 | } 82 | delete[] v; 83 | delete[] q; 84 | } 85 | 86 | int main(){ 87 | 88 | int n = 3; 89 | double** a = new double*[n]; 90 | for(int i = 0; i < n; i++) 91 | a[i] = new double[n]; 92 | 93 | a[0][0] = 0; a[0][1] = -17; a[0][2] = 21; 94 | a[1][0] = 0; a[1][1] = 13; a[1][2] = -15; 95 | a[2][0] = 0; a[2][1] = 10; a[2][2] = -12; 96 | 97 | MaxEval(a, n); 98 | 99 | for(int i = 0; i < n; i++) 100 | delete[] a[i]; 101 | delete[] a; 102 | 103 | return 0; 104 | } 105 | -------------------------------------------------------------------------------- /Max_Eigenvalue_by_ChatGPT.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_ITERATIONS 1000 6 | #define EPSILON 0.00001 7 | 8 | int main() 9 | { 10 | // Define matrix A 11 | double A[3][3] = {{2, -1, 0}, 12 | {-1, 2, -1}, 13 | {0, -1, 2}}; 14 | 15 | // Define initial guess for eigenvector x 16 | double x[3] = {1, 1, 1}; 17 | 18 | // Initialize variables 19 | int i, j, k; 20 | double lambda = 0; 21 | double norm_x, norm_y; 22 | double y[3]; 23 | 24 | // Perform power iteration method 25 | for (k = 0; k < MAX_ITERATIONS; k++) { 26 | // Multiply A by x 27 | for (i = 0; i < 3; i++) { 28 | y[i] = 0; 29 | for (j = 0; j < 3; j++) { 30 | y[i] += A[i][j] * x[j]; 31 | } 32 | } 33 | 34 | // Find the maximum component of y and normalize 35 | norm_y = 0; 36 | for (i = 0; i < 3; i++) { 37 | if (fabs(y[i]) > norm_y) { 38 | norm_y = fabs(y[i]); 39 | } 40 | } 41 | for (i = 0; i < 3; i++) { 42 | x[i] = y[i] / norm_y; 43 | } 44 | 45 | // Compute the corresponding eigenvalue 46 | lambda = 0; 47 | for (i = 0; i < 3; i++) { 48 | lambda += A[i][0] * x[i]; 49 | } 50 | 51 | // Check for convergence 52 | norm_x = 0; 53 | for (i = 0; i < 3; i++) { 54 | norm_x += pow(x[i], 2); 55 | } 56 | norm_x = sqrt(norm_x); 57 | if (fabs(lambda - norm_y) < EPSILON * norm_x) { 58 | break; 59 | } 60 | } 61 | 62 | // Print the maximum eigenvalue 63 | printf("Maximum eigenvalue: %f\n", lambda); 64 | 65 | return 0; 66 | } 67 | -------------------------------------------------------------------------------- /Mesh.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main() { 8 | // Define the domain as a rectangle 9 | double xmin = -1.0; 10 | double xmax = 1.0; 11 | double ymin = -1.0; 12 | double ymax = 1.0; 13 | 14 | // Define the mesh size 15 | double h = 0.1; 16 | 17 | // Define the input for Triangle library 18 | triangulateio in, out; 19 | in.numberofpoints = 4; 20 | in.numberofpointattributes = 0; 21 | in.numberofsegments = 4; 22 | in.numberofholes = 0; 23 | in.pointlist = (REAL*) malloc(in.numberofpoints * 2 * sizeof(REAL)); 24 | in.segmentlist = (int*) malloc(in.numberofsegments * 2 * sizeof(int)); 25 | 26 | // Define the coordinates of the points and segments 27 | in.pointlist[0] = xmin; 28 | in.pointlist[1] = ymin; 29 | in.pointlist[2] = xmin; 30 | in.pointlist[3] = ymax; 31 | in.pointlist[4] = xmax; 32 | in.pointlist[5] = ymax; 33 | in.pointlist[6] = xmax; 34 | in.pointlist[7] = ymin; 35 | 36 | in.segmentlist[0] = 0; 37 | in.segmentlist[1] = 1; 38 | in.segmentlist[2] = 1; 39 | in.segmentlist[3] = 2; 40 | in.segmentlist[4] = 2; 41 | in.segmentlist[5] = 3; 42 | in.segmentlist[6] = 3; 43 | in.segmentlist[7] = 0; 44 | 45 | // Call the Triangle library 46 | std::string options = "p"; 47 | options += "q"; 48 | options += "a"; 49 | std::vector args; 50 | args.push_back(const_cast(options.c_str())); 51 | triangulate(args, &in, &out, NULL); 52 | 53 | // Print the mesh 54 | std::cout << "Mesh points:" << std::endl; 55 | for (int i = 0; i < out.numberofpoints; i++) { 56 | std::cout << out.pointlist[2*i] << " " << out.pointlist[2*i+1] << std::endl; 57 | } 58 | std::cout << "Mesh elements:" << std::endl; 59 | for (int i = 0; i < out.numberoftriangles; i++) { 60 | std::cout << out.trianglelist[3*i] << " " << out.trianglelist[3*i+1] << " " << out.trianglelist[3*i+2] << std::endl; 61 | } 62 | 63 | // Free memory 64 | free(in.pointlist); 65 | free(in.segmentlist); 66 | free(out.pointlist); 67 | free(out.segmentlist); 68 | free(out.trianglelist); 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /PINN.py: -------------------------------------------------------------------------------- 1 | import tensorflow.compat.v1 as tf 2 | tf.disable_v2_behavior() 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | # Define the computational graph 7 | graph = tf.Graph() 8 | with graph.as_default(): 9 | # Define the input tensors 10 | x = tf.placeholder(tf.float32, [None, 1], name='x') 11 | t = tf.placeholder(tf.float32, [None, 1], name='t') 12 | u = tf.placeholder(tf.float32, [None, 1], name='u') 13 | 14 | # Define the neural network architecture 15 | with tf.variable_scope('neural_net'): 16 | h1 = tf.layers.dense(tf.concat([x, t], axis=1), 50, activation=tf.nn.tanh) 17 | h2 = tf.layers.dense(h1, 50, activation=tf.nn.tanh) 18 | h3 = tf.layers.dense(h2, 50, activation=tf.nn.tanh) 19 | pred = tf.layers.dense(h3, 1, activation=None, name='pred') 20 | 21 | # Define the loss function 22 | with tf.variable_scope('loss'): 23 | # Define the PDE residual 24 | u_x, u_t = tf.gradients(pred, [x, t]) 25 | u_xx = tf.gradients(u_x, [x]) 26 | f = u_t - u_xx - tf.cos(x)*(tf.cos(t)-tf.sin(t)) 27 | 28 | # Define the boundary conditions 29 | bc_left = tf.reduce_mean(tf.square(pred[:, 0] - u[:, 0])) 30 | bc_right = tf.reduce_mean(tf.square(pred[:, -1] - u[:, -1])) 31 | 32 | # Define the total loss 33 | loss = bc_left + bc_right + tf.reduce_mean(tf.square(f)) 34 | 35 | # Define the optimizer 36 | with tf.variable_scope('optimizer'): 37 | optimizer = tf.train.AdamOptimizer().minimize(loss) 38 | 39 | # Define the exact solution 40 | def exact_solution(x, t): 41 | return np.cos(x)*np.cos(t) 42 | 43 | # Define the initial and boundary conditions 44 | def initial_condition(x,t): 45 | return np.cos(x)*np.cos(t) 46 | 47 | def boundary_condition(x,t): 48 | return np.cos(x)*np.cos(t) 49 | 50 | # Train the neural network 51 | with tf.Session(graph=graph) as sess: 52 | sess.run(tf.global_variables_initializer()) 53 | 54 | # Generate some training data 55 | x_train = np.random.uniform(-1, 1, (5000, 1)) 56 | t_train = np.random.uniform(0, 1, (5000, 1)) 57 | u_train = exact_solution(x_train, t_train) 58 | 59 | # Set the initial and boundary conditions 60 | u_train[:, 0] = initial_condition(x_train[:, 0], t_train[:, 0]) 61 | u_train[:, -1] = boundary_condition(x_train[:, 0] , t_train[:, 0]) 62 | 63 | # Train the neural network 64 | for i in range(1000): 65 | _, loss_val = sess.run([optimizer, loss], feed_dict={x: x_train, t: t_train, u: u_train}) 66 | 67 | if i % 100 == 0: 68 | print('Step {}: loss = {}'.format(i, loss_val)) 69 | 70 | # Evaluate the neural network on the test data 71 | u_pred_val = sess.run(pred, feed_dict={x: x_train, t: t_train}) 72 | 73 | # Print the mean squared error 74 | mse = np.mean(np.square(u_train - u_pred_val)) 75 | print('Mean squared error: {}'.format(mse)) 76 | 77 | plt.figure(figsize=(6, 6)) 78 | plt.scatter(x_train, t_train, 0.1, color='blue', label='Training points') 79 | plt.xlabel('x') 80 | plt.ylabel('t') 81 | plt.title('Location of training points') 82 | plt.show() 83 | 84 | # Define the grid 85 | x = np.linspace(-1, 1, 100) 86 | t = np.linspace(0, 1, 100) 87 | X, T = np.meshgrid(x, t) 88 | 89 | # Compute the exact solution on the grid 90 | U = exact_solution(X, T) 91 | 92 | # Plot the contour of the solution 93 | plt.contourf(X, T, U,cmap='jet') 94 | plt.colorbar() 95 | plt.xlabel('x') 96 | plt.ylabel('t') 97 | plt.title('Exact Solution') 98 | plt.show() 99 | 100 | # Plot the contour of the prediction 101 | plt.scatter(x_train, t_train, 1.0, u_pred_val[:,0], cmap='jet') 102 | cbar= plt.colorbar() 103 | plt.xlabel('x') 104 | plt.ylabel('t') 105 | plt.title('Predicted Solution') 106 | plt.show() 107 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ChatGPT for Programming Numerical Methods 2 | ![pic](./image.png) 3 | 4 | **Programming numerical methods using ChatGPT: successes, failures, and challenges** 5 | 6 | **Research Article:**
7 | **[ChatGPT for Programming Numerical Methods](https://www.dl.begellhouse.com/journals/558048804a15188a,498820861ef102d2,1255e053242c9a40.html)**
8 | This is also the **[arXiv](https://arxiv.org/pdf/2303.12093.pdf)** version.
9 | 10 | **Authors:** Ali Kashefi (kashefi@stanford.edu) & Tapan Mukerji (mukerji@stanford.edu)
11 | **Version:** 2.0
12 | 13 | **Citation**
14 | If you use this research article, please cite the following journal paper:
15 | **[ChatGPT for Programming Numerical Methods](https://www.dl.begellhouse.com/journals/558048804a15188a,498820861ef102d2,1255e053242c9a40.html)** 16 | 17 | @article{kashefi2023chatgpt, 18 | title={Chatgpt for programming numerical methods}, 19 | author={Kashefi, Ali and Mukerji, Tapan}, 20 | journal={Journal of Machine Learning for Modeling and Computing}, 21 | volume={4}, 22 | number={2}, 23 | year={2023}, 24 | publisher={Begel House Inc.}} 25 | 26 | **Abstract** 27 | 28 | ChatGPT is a large language model recently released by the OpenAI company. In this technical report, we explore for the first time the capability of ChatGPT for programming numerical algorithms. Specifically, we examine the capability of GhatGPT for generating codes for numerical algorithms in different programming languages, for debugging and improving written codes by users, for completing missed parts of numerical codes, rewriting available codes in other programming languages, and for parallelizing serial codes. Additionally, we assess if ChatGPT can recognize if given codes are written by humans or machines. To reach this goal, we consider a variety of mathematical problems such as the Poisson equation, the diffusion equation, the incompressible Navier-Stokes equations, compressible inviscid flow, eigenvalue problems, solving linear systems of equations, storing sparse matrices, etc. Furthermore, we exemplify scientific machine learning such as physics-informed neural networks and convolutional neural networks with applications to computational physics. Through these examples, we investigate the successes, failures, and challenges of ChatGPT. Examples of failures are producing singular matrices, operations on arrays with incompatible sizes, programming interruption for relatively long codes, etc. Our outcomes suggest that ChatGPT can successfully program numerical algorithms in different programming languages, but certain limitations and challenges exist that require further improvement of this machine learning model. 29 | 30 | **ChatGPT in Machine Learning + X seminar 2023 at Brown University**
31 | In case of your interest, you might watch the recorded machine learning seminar with the topic of ChatGPT at Brown University using the following link:
32 | [YouTube Video](https://www.youtube.com/watch?v=zFrZsufbNSA&t=3595s) 33 | 34 | **Questions?**
35 | If you have any questions or need assistance, please do not hesitate to contact Ali Kashefi (kashefi@stanford.edu) via email. 36 | 37 | **About the Author**
38 | Please see the author's website: [Ali Kashefi](https://web.stanford.edu/~kashefi/) 39 | -------------------------------------------------------------------------------- /SOR_C_language.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define MAX_ITER 1000 6 | 7 | void sor(double **A, double *b, double *x, int n, double omega, double tol) { 8 | int iter_count = 0; 9 | double residual = 0.0; 10 | double *old_x = (double*) malloc(n * sizeof(double)); 11 | 12 | do { 13 | iter_count++; 14 | residual = 0.0; 15 | 16 | for (int i = 0; i < n; i++) { 17 | old_x[i] = x[i]; 18 | double sigma = 0.0; 19 | 20 | for (int j = 0; j < n; j++) { 21 | if (j != i) { 22 | sigma += A[i][j] * x[j]; 23 | } 24 | } 25 | 26 | x[i] = (1.0 - omega) * x[i] + (omega / A[i][i]) * (b[i] - sigma); 27 | residual += pow(b[i] - A[i][0] * x[0] - A[i][1] * x[1] - A[i][2] * x[2], 2.0); 28 | } 29 | 30 | residual = sqrt(residual); 31 | 32 | } while (residual > tol && iter_count < MAX_ITER); 33 | 34 | printf("Solution:\n"); 35 | for (int i = 0; i < n; i++) { 36 | printf("%.8f ", x[i]); 37 | } 38 | printf("\n"); 39 | 40 | printf("Number of iterations: %d\n", iter_count); 41 | 42 | free(old_x); 43 | } 44 | 45 | int main() { 46 | double **A = (double**) malloc(3 * sizeof(double*)); 47 | for (int i = 0; i < 3; i++) { 48 | A[i] = (double*) malloc(3 * sizeof(double)); 49 | } 50 | 51 | A[0][0] = 4.0; 52 | A[0][1] = 1.0; 53 | A[0][2] = 1.0; 54 | A[1][0] = 1.0; 55 | A[1][1] = 4.0; 56 | A[1][2] = 1.0; 57 | A[2][0] = 1.0; 58 | A[2][1] = 1.0; 59 | A[2][2] = 4.0; 60 | 61 | double b[3] = {1.0, 2.0, 3.0}; 62 | double x[3] = {0.0, 0.0, 0.0}; 63 | 64 | double omega = 1.5; 65 | double tol = 1e-6; 66 | 67 | sor(A, b, x, 3, omega, tol); 68 | 69 | for (int i = 0; i < 3; i++) { 70 | free(A[i]); 71 | } 72 | free(A); 73 | 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /SOR_Cplus_language.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MAX_ITER 1000 5 | 6 | using namespace std; 7 | 8 | void sor(double **A, double *b, double *x, int n, double omega, double tol) { 9 | int iter_count = 0; 10 | double residual = 0.0; 11 | double *old_x = new double[n]; 12 | 13 | do { 14 | iter_count++; 15 | residual = 0.0; 16 | 17 | for (int i = 0; i < n; i++) { 18 | old_x[i] = x[i]; 19 | double sigma = 0.0; 20 | 21 | for (int j = 0; j < n; j++) { 22 | if (j != i) { 23 | sigma += A[i][j] * x[j]; 24 | } 25 | } 26 | 27 | x[i] = (1.0 - omega) * x[i] + (omega / A[i][i]) * (b[i] - sigma); 28 | residual += pow(b[i] - A[i][0] * x[0] - A[i][1] * x[1] - A[i][2] * x[2], 2.0); 29 | } 30 | 31 | residual = sqrt(residual); 32 | 33 | } while (residual > tol && iter_count < MAX_ITER); 34 | 35 | cout << "Solution:\n"; 36 | for (int i = 0; i < n; i++) { 37 | cout << x[i] << " "; 38 | } 39 | cout << endl; 40 | 41 | cout << "Number of iterations: " << iter_count << endl; 42 | 43 | delete[] old_x; 44 | } 45 | 46 | int main() { 47 | double **A = new double*[3]; 48 | for (int i = 0; i < 3; i++) { 49 | A[i] = new double[3]; 50 | } 51 | 52 | A[0][0] = 4.0; 53 | A[0][1] = 1.0; 54 | A[0][2] = 1.0; 55 | A[1][0] = 1.0; 56 | A[1][1] = 4.0; 57 | A[1][2] = 1.0; 58 | A[2][0] = 1.0; 59 | A[2][1] = 1.0; 60 | A[2][2] = 4.0; 61 | 62 | double b[3] = {1.0, 2.0, 3.0}; 63 | double x[3] = {0.0, 0.0, 0.0}; 64 | 65 | double omega = 1.5; 66 | double tol = 1e-6; 67 | 68 | sor(A, b, x, 3, omega, tol); 69 | 70 | for (int i = 0; i < 3; i++) { 71 | delete[] A[i]; 72 | } 73 | delete[] A; 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /SOR_Julia_language.jl: -------------------------------------------------------------------------------- 1 | # Successive over-relaxation (SOR) method for solving a linear system of equations 2 | # Ax = b 3 | # Example: solve 4x1 + x2 + x3 = 1, x1 + 4x2 + x3 = 2, x1 + x2 + 4x3 = 3 4 | # using SOR method with omega = 1.5 and tolerance = 1e-6 5 | 6 | # Set up the system of equations 7 | A = [4 1 1; 1 4 1; 1 1 4] 8 | b = [1; 2; 3] 9 | 10 | # Set up initial guess 11 | x = [0; 0; 0] 12 | 13 | # Set up relaxation parameter and tolerance 14 | omega = 1.5 15 | tol = 1e-6 16 | 17 | # Set up maximum number of iterations 18 | max_iter = 1000 19 | 20 | # Solve the system of equations using SOR method 21 | for iter_count = 1:max_iter 22 | old_x = copy(x) 23 | for i = 1:length(x) 24 | sigma = 0 25 | for j = 1:length(x) 26 | if j != i 27 | sigma += A[i,j]*x[j] 28 | end 29 | end 30 | x[i] = (1 - omega)*x[i] + (omega/A[i,i])*(b[i] - sigma) 31 | end 32 | residual = norm(b - A*x) 33 | if residual < tol 34 | break 35 | end 36 | end 37 | 38 | # Display the solution and number of iterations 39 | println("Solution:") 40 | println(x) 41 | println("Number of iterations: ", iter_count) 42 | -------------------------------------------------------------------------------- /SOR_MATLAB_language.m: -------------------------------------------------------------------------------- 1 | % Successive over-relaxation (SOR) method for solving a linear system of equations 2 | % Ax = b 3 | % Example: solve 4x1 + x2 + x3 = 1, x1 + 4x2 + x3 = 2, x1 + x2 + 4x3 = 3 4 | % using SOR method with omega = 1.5 and tolerance = 1e-6 5 | 6 | % Set up the system of equations 7 | A = [4 1 1; 1 4 1; 1 1 4]; 8 | b = [1; 2; 3]; 9 | 10 | % Set up initial guess 11 | x = [0; 0; 0]; 12 | 13 | % Set up relaxation parameter and tolerance 14 | omega = 1.5; 15 | tol = 1e-6; 16 | 17 | % Set up maximum number of iterations 18 | max_iter = 1000; 19 | 20 | % Solve the system of equations using SOR method 21 | for iter_count = 1:max_iter 22 | old_x = x; 23 | for i = 1:length(x) 24 | sigma = 0; 25 | for j = 1:length(x) 26 | if j ~= i 27 | sigma = sigma + A(i,j)*x(j); 28 | end 29 | end 30 | x(i) = (1 - omega)*x(i) + (omega/A(i,i))*(b(i) - sigma); 31 | end 32 | residual = norm(b - A*x); 33 | if residual < tol 34 | break 35 | end 36 | end 37 | 38 | % Display the solution and number of iterations 39 | disp(['Solution:']); 40 | disp(x); 41 | disp(['Number of iterations: ' num2str(iter_count)]); 42 | -------------------------------------------------------------------------------- /SOR_Python_language.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def sor(A, b, x0, omega, tol, max_iter): 4 | """ 5 | Solves the linear system of equations Ax = b using the method of successive over-relaxation (SOR). 6 | 7 | Parameters: 8 | A (numpy.ndarray): the coefficient matrix of the linear system. 9 | b (numpy.ndarray): the right-hand side vector of the linear system. 10 | x0 (numpy.ndarray): the initial guess for the solution vector. 11 | omega (float): the relaxation parameter. 12 | tol (float): the tolerance for the residual. 13 | max_iter (int): the maximum number of iterations. 14 | 15 | Returns: 16 | numpy.ndarray: the solution vector. 17 | int: the number of iterations performed. 18 | """ 19 | 20 | x = np.copy(x0) 21 | n = len(x) 22 | iter_count = 0 23 | residual = np.linalg.norm(b - A @ x) 24 | 25 | while residual > tol and iter_count < max_iter: 26 | iter_count += 1 27 | for i in range(n): 28 | old_x_i = x[i] 29 | x[i] += omega * ((b[i] - A[i, :] @ x) / A[i, i] - x[i]) 30 | residual = np.linalg.norm(b - A @ x) 31 | if residual <= tol: 32 | break 33 | if np.allclose(x, old_x_i): 34 | break 35 | 36 | return x, iter_count 37 | 38 | # Define the coefficient matrix A, the right-hand side vector b, and the initial guess x0 39 | A = np.array([[4, 1, 1], [1, 4, 1], [1, 1, 4]]) 40 | b = np.array([1, 2, 3]) 41 | x0 = np.array([0, 0, 0]) 42 | 43 | # Solve the linear system using SOR 44 | omega = 1.5 45 | tol = 1e-6 46 | max_iter = 1000 47 | x, iter_count = sor(A, b, x0, omega, tol, max_iter) 48 | 49 | # Print the solution and the number of iterations 50 | print("Solution:", x) 51 | print("Number of iterations:", iter_count) 52 | -------------------------------------------------------------------------------- /Thomas_Incomplete_Code.cpp: -------------------------------------------------------------------------------- 1 | #define _USE_MATH_DEFINES 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std ; 8 | 9 | void Tridiagonal(int n, double a[], double b[], double c[], double d[], double x[]){ 10 | 11 | for(int i = 1 ; i < n ; i ++){ 12 | 13 | b[i] = b[i] - (a[i]/b[i-1])*c[i-1] ; 14 | d[i] = d[i] - (a[i]/b[i-1])*d[i-1] ; 15 | } 16 | 17 | x[n-1] = d[n-1]/b[n-1] ; 18 | cout << "x"<< n << " " << x[n-1] << endl ; 19 | 20 | for(int i = n - 2; i > -1 ; i --){ 21 | } 22 | 23 | return ; 24 | } 25 | 26 | int main(){ 27 | 28 | int n = 4 ; 29 | double *a, *b, *c, *d, *x ; 30 | a = new double[n] ; 31 | b = new double[n] ; 32 | c = new double[n] ; 33 | d = new double[n] ; 34 | x = new double[n] ; 35 | 36 | for(int i = 0 ; i < n ; i ++) 37 | x[i] = 0 ; 38 | 39 | a[0] = 0. ; 40 | c[n-1] = 0. ; 41 | 42 | // As an example 43 | // Please look at the wiki-page for the definition of a[] b[] c[] d[] 44 | a[1] = a[2] = a[3] = -1 ; 45 | c[0] = c[1] = c[2] = -1 ; 46 | b[0] = b[1] = b[2] = b[3] = 2 ; 47 | d[0] = d[1] = d[2] = d[3] = 1 ; 48 | 49 | Tridiagonal(n, a, b, c, d, x) ; 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ali-Stanford/ChatGPT_Programming_Numerical_Methods/5b5078593d78057cdb61d3f3664253e1de8d3d15/image.png -------------------------------------------------------------------------------- /secant.py: -------------------------------------------------------------------------------- 1 | def secant_method(f, x0, x1, tol=1e-6, max_iter=100): 2 | """ 3 | Implements the secant method to find a root of a function f. 4 | 5 | Args: 6 | f: callable function of one variable 7 | x0: initial guess for the root 8 | x1: second initial guess for the root 9 | tol: tolerance for convergence (default=1e-6) 10 | max_iter: maximum number of iterations (default=100) 11 | 12 | Returns: 13 | x: estimate of the root 14 | """ 15 | i = 0 16 | while i < max_iter: 17 | x = x1 - ((f(x1)*(x1 - x0)) / (f(x1) - f(x0))) 18 | if abs(x - x1) < tol: 19 | return x 20 | x0 = x1 21 | x1 = x 22 | i += 1 23 | raise ValueError("Secant method failed to converge.") 24 | --------------------------------------------------------------------------------