Date: 2025-03-29T05:58:42+00:00

Actual source code: rand.c

      1: #include <petsc/private/randomimpl.h>

      3: static PetscErrorCode PetscRandomSeed_Rand(PetscRandom r)
      4: {
      5:   PetscFunctionBegin;
      6:   srand((unsigned int)r->seed);
      7:   PetscFunctionReturn(PETSC_SUCCESS);
      8: }

     10: #define RAND_WRAP ((PetscReal)(rand() / (double)((unsigned int)RAND_MAX + 1)))
     11: static PetscErrorCode PetscRandomGetValue_Rand(PetscRandom r, PetscScalar *val)
     12: {
     13:   PetscFunctionBegin;
     14: #if defined(PETSC_USE_COMPLEX)
     15:   if (r->iset) *val = PetscRealPart(r->width) * RAND_WRAP + PetscRealPart(r->low) + (PetscImaginaryPart(r->width) * RAND_WRAP + PetscImaginaryPart(r->low)) * PETSC_i;
     16:   else *val = RAND_WRAP + RAND_WRAP * PETSC_i;
     17: #else
     18:   if (r->iset) *val = r->width * RAND_WRAP + r->low;
     19:   else *val = RAND_WRAP;
     20: #endif
     21:   PetscFunctionReturn(PETSC_SUCCESS);
     22: }

     24: static PetscErrorCode PetscRandomGetValueReal_Rand(PetscRandom r, PetscReal *val)
     25: {
     26:   PetscFunctionBegin;
     27: #if defined(PETSC_USE_COMPLEX)
     28:   if (r->iset) *val = PetscRealPart(r->width) * RAND_WRAP + PetscRealPart(r->low);
     29:   else *val = RAND_WRAP;
     30: #else
     31:   if (r->iset) *val = r->width * RAND_WRAP + r->low;
     32:   else *val = RAND_WRAP;
     33: #endif
     34:   PetscFunctionReturn(PETSC_SUCCESS);
     35: }

     37: static struct _PetscRandomOps PetscRandomOps_Values = {
     38:   PetscDesignatedInitializer(seed, PetscRandomSeed_Rand),
     39:   PetscDesignatedInitializer(getvalue, PetscRandomGetValue_Rand),
     40:   PetscDesignatedInitializer(getvaluereal, PetscRandomGetValueReal_Rand),
     41:   PetscDesignatedInitializer(getvalues, NULL),
     42:   PetscDesignatedInitializer(getvaluesreal, NULL),
     43:   PetscDesignatedInitializer(destroy, NULL),
     44:   PetscDesignatedInitializer(setfromoptions, NULL),
     45: };

     47: /*MC
     48:    PETSCRAND - access to the basic Unix random number generator

     50:    Options Database Key:
     51: . -random_type <rand,rand48,sprng> - set the random number generator from the options database

     53:   Level: beginner

     55:   Note:
     56:   Not recommended since it can produce different numbers on different systems

     58: .seealso: `PetscRandomCreate()`, `PetscRandomSetType()`, `PETSCRAND48`, `PETSCSPRNG`, `PetscRandomSetFromOptions()`, `PetscRandomType`
     59: M*/

     61: PETSC_EXTERN PetscErrorCode PetscRandomCreate_Rand(PetscRandom r)
     62: {
     63:   PetscFunctionBegin;
     64:   r->ops[0] = PetscRandomOps_Values;
     65:   PetscCall(PetscObjectChangeTypeName((PetscObject)r, PETSCRAND));
     66:   PetscFunctionReturn(PETSC_SUCCESS);
     67: }