You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.3 KiB
C
51 lines
1.3 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <time.h>
|
|
#include <math.h>
|
|
#include <mpi.h>
|
|
|
|
|
|
int main(int argc, char *argv[]) {
|
|
if(argc != 2) {
|
|
fprintf(stderr, "Uso: %s <tiros>\n", argv[0]);
|
|
return 1;
|
|
}
|
|
|
|
int mi_rank, num_procs;
|
|
MPI_Init(&argc, &argv);
|
|
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
|
|
MPI_Comm_rank(MPI_COMM_WORLD, &mi_rank);
|
|
|
|
if(! mi_rank)
|
|
printf("Procesos: %d\n", num_procs);
|
|
|
|
srand(time(NULL) + mi_rank); // Ojo, tal vez un proceso se lanza un segundo después que otro y esta cuenta coincide.
|
|
|
|
long tiros = atol(argv[1]);
|
|
tiros = tiros / num_procs * num_procs;
|
|
|
|
long positivos_parciales = 0;
|
|
for(long i = 0; i < tiros / num_procs; i++) {
|
|
double x = (double)rand() / RAND_MAX;
|
|
double y = (double)rand() / RAND_MAX;
|
|
if(x * x + y * y < 1)
|
|
positivos_parciales++;
|
|
}
|
|
|
|
long positivos;
|
|
MPI_Reduce(&positivos_parciales, &positivos, 1, MPI_LONG, MPI_SUM, 0, MPI_COMM_WORLD);
|
|
|
|
if(! mi_rank) {
|
|
double pi = 4.0 * positivos / tiros;
|
|
|
|
printf("Tiros = %ld, Positivos = %ld\n", tiros, positivos);
|
|
printf("π ~= %.15f\n", pi);
|
|
printf("ε = %f%%\n", 100 * fabs(M_PI - pi) / M_PI);
|
|
}
|
|
|
|
MPI_Finalize();
|
|
|
|
return 0;
|
|
}
|
|
|