Actual source code: ex1.c

petsc-3.10.5 2019-03-28
Report Typos and Errors

  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;
 18:   PetscMPIInt    rank;
 19:   PetscInt       view_rank=-1;
 20: #if defined(PETSC_USE_LOG)
 21:   PetscLogEvent  event;
 22: #endif

 24:   PetscInitialize(&argc,&argv,(char*)0,help);if (ierr) return ierr;
 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) {
 39:       PetscPrintf(PETSC_COMM_SELF,"[%d] value[%D] = %6.4e\n",rank,i,(double)PetscRealPart(value));
 40:     }
 41:     values[i] = (PetscInt)(n*PetscRealPart(value) + 2.0);
 42:   }
 43:   avg = avg/((PetscReal)n);
 44:   if (view_rank == (PetscInt)rank) {
 45:     PetscPrintf(PETSC_COMM_SELF,"[%d] Average value %6.4e\n",rank,(double)PetscRealPart(avg));
 46:   }

 48:   PetscSortInt(n,values);

 50:   PetscLogEventRegister("Sort",0,&event);
 51:   PetscLogEventBegin(event,0,0,0,0);

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

 62:   for (i=1; i<n; i++) {
 63:     if (values[i] < values[i-1]) SETERRQ(PETSC_COMM_SELF,1,"Values not sorted");
 64:   }
 65:   PetscFree(values);
 66:   PetscRandomDestroy(&rnd);

 68:   PetscFinalize();
 69:   return ierr;
 70: }



 74: /*TEST

 76:    test:

 78:    test:
 79:       suffix: 2
 80:       nsize: 2
 81:       output_file: output/ex1_1.out

 83:    test:
 84:       suffix: 3
 85:       args: -view_randomvalues 0

 87: TEST*/