#include<stdio.h>
#include<mpi.h>
#include<stdlib.h>
#include<time.h>
#include <windows.h>
double Trap(double left_endpt, double right_endpt, int trap_count, double base_1en);
double f(double x);
int main(int argc, char* argv[]) {
int done = 0, my_rank, comm_sz, n = 10000000, local_n;
double a = 0.0, b = 1.0, h, local_a, local_b;
double local_int, total_int;
int source;
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
double startwtime = 0.0, endwtime;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);//进程号
MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);//进程总数
MPI_Get_processor_name(processor_name, &namelen);//获取处理器名称
fprintf(stderr, "Process %d of %d on %s \n",my_rank, comm_sz, processor_name);
while (!done) {
if (my_rank == 0) {
fprintf(stdout, "Enter the number of intervals: (0 quits) ");
fflush(stdout);
if (scanf_s("%d", &n) != 1) {
fprintf(stdout, "No number entered; quitting\n");
n = 0;
}
startwtime = MPI_Wtime();
}
if (n == 0)
{
done = 1;
}
else {
h = (b - a) / n; /* h is the same for a11 processes */ //间距
local_n = n / comm_sz; /* So is the number of trapezoids */ //
local_a = a + my_rank * local_n * h;
local_b = local_a + local_n * h;
local_int = Trap(local_a, local_b, local_n, h);
//printf("localdata my_rank:%d comm_sz:%d processor_name:%s\n", my_rank, comm_sz, processor_name);
//printf("localVar local_n:%d local_a:%f local_b:%f local_int:%f \n\n", local_n, local_a, local_b, local_int);
if (my_rank != 0) {
MPI_Send(&local_int, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
} //发送缓冲区的起始地址,将发送的数据个数(非负整数),数据类型,目的进程标识号,消息标志,通信域
else
{
total_int = local_int;
for (source = 1; source < comm_sz; source++) {
MPI_Recv(&local_int, 1, MPI_DOUBLE, source, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
total_int += local_int;
}
}
if (my_rank == 0) {
printf("With n = %d trapezoids, our estimate\n", n);
printf("of the integral from %f to %f = %.15e\n", a, b, total_int);
endwtime = MPI_Wtime();
printf("wall clock time = %f\n", endwtime - startwtime);
}
}
}
MPI_Finalize();
return 0;
}/* main */
double Trap(
double left_endpt,
double right_endpt,
int trap_count,
double base_1en) {
double estimate, x;
int i;
estimate = (f(left_endpt) + f(right_endpt)) / 2.0;
for (i = 1; i <= trap_count - 1; i++) {
x = left_endpt + i * base_1en;
estimate += f(x);
}
estimate = estimate * base_1en;
return estimate;
}/*Trap*/
double f(double x) {
return x * x;
}
MPI并行求积分
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 话费充值:快充话费、折扣话费、三网话费充值、 加油卡充值:中石油加油卡充值、中石化加油卡充值、 交通出行:美团摩拜...
- 微信诞生5年,坐拥用户9亿,月活跃用户约6亿。对于这个互联网巨无霸。按理来说,各项用户体验都该让人舒适满意。 但微...