1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- // 包括库 --- Include libraries
- #include <stdio.h>
- #include <math.h>
- // 定义 --- Definitions
- #define N 256 // 空间网格数 --- Number of spatial grid points
- #define T 255 // 时间步数 --- Time steps to be simulated (integrated)
- #define dt 1 // 时间步长 --- Temporal length scale (dt)
- #define dx 1 // 空间步长 --- Spatial length scale (dx
- #define alpha 0.5 // 扩散系数 --- Diffusion coefficient
- // 全球结构 --- Global structures
- struct simulation_data{
- double u[N]; // u: 为当前时刻的浓度分
- // --- To store the concentration distribution at the current moment
- int generation; // generation: 模拟迭代 --- simulation iteration
- } state;
- // 打印功能 --- Print function (truncated)
- void printGrid(double grid[N], int time) {
- // 代 --- generations
- printf("[dt x %d]\t", time);
- // 最左边3个格点的状态 --- state of the 3 left-most lattice sites
- for (int i = 0; i < 3;i++){
- printf("%.2f ", grid[i]);
- printf("\t");
- }
- printf("...\t");
- // 三个中心格点的状态 --- state of the 3 center lattice sites
- for (int i = floor(N/2)-1 ; i < floor(N/2)+2;i++){
- printf("%.2f ", grid[i]);
- printf("\t");
- }
- printf("...\t");
- // 3个最右边格点的状态 --- state of the 3 right-most lattice sites
- for (int i = N-3; i < N;i++){
- printf("%.2f ", grid[i]);
- printf("\t");
- }
- printf("\n");
- }
- // 初始化功能 --- Initialization function
- void init_lattice(void){
- // 初始化浓度分布 --- Initialize concentration distribution
- for (int i = 0; i < N; i++) {
- if (i >= 45*N/100 && i <= 55*N/100) {
- state.u[i] = 100.0;
- } else {
- state.u[i] = 0.0;
- }
- }
- // 初始化时间 --- Initialize time
- state.generation = 0;
- }
- // 更新功能 --- Update function (to increment one iteration/generation)
- void update_lattice(void){
- // u_new: 为下一个时刻的浓度分布
- double u_new[N];// --- To store the concentration distribution at the next moment
- // 强制边界条件 --- Enforce boundary condition
- u_new[0] = state.u[0];
- u_new[N] = state.u[N];
- // 内部节点计算 --- Internal node calculation
- for (int i = 1; i < N; i++) {
- u_new[i] = state.u[i] + alpha * dt / (dx*dx) * (state.u[i+1] - 2*state.u[i] + state.u[i-1]);
- }
- // 更新浓度分布 --- Update concentration distribution
- for (int i = 0; i < N; i++) {
- state.u[i] = u_new[i];
- }
- //printGrid(state.u,state.generation);
- state.generation ++;
- }
- // 模拟 --- simulation
- void integrate_simulation(void){
- // 初始化模拟 --- Initialize simulation
- init_lattice();
- printGrid(state.u, state.generation);
- // 迭代计算 --- Iterative calculation
- for (int t = 1; t <= T; t++) {
- update_lattice();
- printGrid(state.u, state.generation);
- }
- }
- // 主要功能 --- Main function
- int main(int argc, char **argv) {
- integrate_simulation();
- return 0;
- }
|