📄 2007280037_maixin_simulated_annealing.c
字号:
#include <mpi.h>#include <math.h>#include <stdio.h>#include <stdlib.h> #define NUM_TOTAL_ITERATIONS 100#define NUM_DATA_POINTS 4096int main(int argc, char **argv) { /* MPI information */ int p, myid; /* loop variables*/ int i, j; int x_new; double t; double err; /* data accross each CPU */ double f[NUM_DATA_POINTS]; double T; // temperature unsigned int x[2]; // position double c[2]; // cost /* Initialize MPI */ MPI_Init(&argc, &argv); /* Get configuration parameters */ MPI_Comm_size(MPI_COMM_WORLD,&p); MPI_Comm_rank(MPI_COMM_WORLD,&myid); /* Initialization on each CPU */ for (i = 0; i < NUM_DATA_POINTS; i++) { t = (double)i / NUM_DATA_POINTS; f[i] = 5*t*(t-1)*cos(7*M_PI*t) + 1/10 *cos(100*M_PI*t); printf("f(%d)=%f", i, f[i]); } x[myid] = NUM_DATA_POINTS * rand() / (RAND_MAX + 1); // in [0, NUM_DATA_POINTS - 1] c[myid] = f[ x[myid] ]; printf("x(%d): %f \n\n\n", 0, x[myid]); /* Loop */ for( j = 0; j < NUM_TOTAL_ITERATIONS; j++){ /* Simulated annealing algorithm */ for (T = NUM_DATA_POINTS; T >= 1; T /= 2) // cooling schedule { x_new = (int) x[myid] + T * ( -1 + 2*rand() / RAND_MAX ); x_new %= NUM_DATA_POINTS; if( f[x_new] < c[myid] ){ x[myid] = x_new; c[myid] = f[x_new]; } } /* Broadcast values and synchronize*/ for (i = 0; i < 2; ++i) { MPI_Bcast( x + i, 1, MPI_DOUBLE, i, MPI_COMM_WORLD); MPI_Bcast( c + i, 1, MPI_DOUBLE, i, MPI_COMM_WORLD); } MPI_Barrier(MPI_COMM_WORLD); /* Keep minimum value */ if( c[1 - myid] < c[myid] ){ c[myid] = c[1 - myid]; x[myid] = x[1 - myid]; } /* Print result and error information */ if( myid == 0) { err = (x[myid] - 0.57)*(x[myid] - 0.57); printf("x(%d): %d err2=%f\n", j, x[myid], err); } } MPI_Finalize(); return 0;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -