1 2 static char help[] = "Tests PetscRandom functions.\n\n"; 3 4 #include <petscsys.h> 5 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 */ 11 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 22 23 PetscCall(PetscInitialize(&argc,&argv,(char*)0,help)); 24 PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD,&rank)); 25 PetscCall(PetscOptionsGetInt(NULL,NULL,"-n",&n,NULL)); 26 PetscCall(PetscOptionsGetInt(NULL,NULL,"-view_randomvalues",&view_rank,NULL)); 27 28 PetscCall(PetscRandomCreate(PETSC_COMM_WORLD,&rnd)); 29 /* force imaginary part of random number to always be zero; thus obtain reproducible results with real and complex numbers */ 30 PetscCall(PetscRandomSetInterval(rnd,0.0,1.0)); 31 PetscCall(PetscRandomSetFromOptions(rnd)); 32 33 PetscCall(PetscMalloc1(n,&values)); 34 for (i=0; i<n; i++) { 35 PetscCall(PetscRandomGetValue(rnd,&value)); 36 avg += value; 37 if (view_rank == (PetscInt)rank) { 38 PetscCall(PetscPrintf(PETSC_COMM_SELF,"[%d] value[%" PetscInt_FMT "] = %6.4e\n",rank,i,(double)PetscRealPart(value))); 39 } 40 values[i] = (PetscInt)(n*PetscRealPart(value) + 2.0); 41 } 42 avg = avg/((PetscReal)n); 43 if (view_rank == (PetscInt)rank) { 44 PetscCall(PetscPrintf(PETSC_COMM_SELF,"[%d] Average value %6.4e\n",rank,(double)PetscRealPart(avg))); 45 } 46 47 PetscCall(PetscSortInt(n,values)); 48 49 PetscCall(PetscLogEventRegister("Sort",0,&event)); 50 PetscCall(PetscLogEventBegin(event,0,0,0,0)); 51 52 PetscCall(PetscRandomSeed(rnd)); 53 for (i=0; i<n; i++) { 54 PetscCall(PetscRandomGetValue(rnd,&value)); 55 values[i] = (PetscInt)(n*PetscRealPart(value) + 2.0); 56 /* printf("value[%d] = %g\n",i,value); */ 57 } 58 PetscCall(PetscSortInt(n,values)); 59 PetscCall(PetscLogEventEnd(event,0,0,0,0)); 60 61 for (i=1; i<n; i++) { 62 PetscCheckFalse(values[i] < values[i-1],PETSC_COMM_SELF,PETSC_ERR_PLIB,"Values not sorted"); 63 } 64 PetscCall(PetscFree(values)); 65 PetscCall(PetscRandomDestroy(&rnd)); 66 67 PetscCall(PetscFinalize()); 68 return 0; 69 } 70 71 /*TEST 72 73 test: 74 75 test: 76 suffix: 2 77 nsize: 2 78 output_file: output/ex1_1.out 79 80 test: 81 suffix: 3 82 args: -view_randomvalues 0 83 84 TEST*/ 85