Actual source code: ex1.c


  2: static char help[] = "Tests PetscRandom functions.\n\n";

  4: #include <petscsys.h>

  6: /* Usage:
  7:    mpiexec -n <np> ./ex1 -n <num_of_random_numbers> -random_type <type> -log_view
  8:                          -view_randomvalues <view_rank>
  9:                          -random_view ascii -random_view :filename
 10: */

 12: int main(int argc, char **argv)
 13: {
 14:   PetscInt    i, n = 1000, *values;
 15:   PetscRandom rnd;
 16:   PetscScalar value, avg = 0.0;
 17:   PetscMPIInt rank;
 18:   PetscInt    view_rank = -1;
 19: #if defined(PETSC_USE_LOG)
 20:   PetscLogEvent event;
 21: #endif

 24:   PetscInitialize(&argc, &argv, (char *)0, help);
 25:   MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
 26:   PetscOptionsGetInt(NULL, NULL, "-n", &n, NULL);
 27:   PetscOptionsGetInt(NULL, NULL, "-view_randomvalues", &view_rank, NULL);

 29:   PetscRandomCreate(PETSC_COMM_WORLD, &rnd);
 30:   /* force imaginary part of random number to always be zero; thus obtain reproducible results with real and complex numbers */
 31:   PetscRandomSetInterval(rnd, 0.0, 1.0);
 32:   PetscRandomSetFromOptions(rnd);

 34:   PetscMalloc1(n, &values);
 35:   for (i = 0; i < n; i++) {
 36:     PetscRandomGetValue(rnd, &value);
 37:     avg += value;
 38:     if (view_rank == (PetscInt)rank) PetscPrintf(PETSC_COMM_SELF, "[%d] value[%" PetscInt_FMT "] = %6.4e\n", rank, i, (double)PetscRealPart(value));
 39:     values[i] = (PetscInt)(n * PetscRealPart(value) + 2.0);
 40:   }
 41:   avg = avg / ((PetscReal)n);
 42:   if (view_rank == (PetscInt)rank) PetscPrintf(PETSC_COMM_SELF, "[%d] Average value %6.4e\n", rank, (double)PetscRealPart(avg));

 44:   PetscSortInt(n, values);

 46:   PetscLogEventRegister("Sort", 0, &event);
 47:   PetscLogEventBegin(event, 0, 0, 0, 0);

 49:   PetscRandomSeed(rnd);
 50:   for (i = 0; i < n; i++) {
 51:     PetscRandomGetValue(rnd, &value);
 52:     values[i] = (PetscInt)(n * PetscRealPart(value) + 2.0);
 53:     /* printf("value[%d] = %g\n",i,value); */
 54:   }
 55:   PetscSortInt(n, values);
 56:   PetscLogEventEnd(event, 0, 0, 0, 0);

 59:   PetscFree(values);
 60:   PetscRandomDestroy(&rnd);

 62:   PetscFinalize();
 63:   return 0;
 64: }

 66: /*TEST

 68:    test:

 70:    test:
 71:       suffix: 2
 72:       nsize: 2
 73:       output_file: output/ex1_1.out

 75:    test:
 76:       suffix: 3
 77:       args: -view_randomvalues 0

 79: TEST*/