xref: /petsc/src/sys/classes/random/impls/rand/rand.c (revision 98d129c30f3ee9fdddc40fdbc5a989b7be64f888)
1 #include <petsc/private/randomimpl.h>
2 
3 static PetscErrorCode PetscRandomSeed_Rand(PetscRandom r)
4 {
5   PetscFunctionBegin;
6   srand(r->seed);
7   PetscFunctionReturn(PETSC_SUCCESS);
8 }
9 
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 }
23 
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 }
36 
37 static struct _PetscRandomOps PetscRandomOps_Values = {
38   PetscDesignatedInitializer(seed, PetscRandomSeed_Rand),
39   PetscDesignatedInitializer(getvalue, PetscRandomGetValue_Rand),
40   PetscDesignatedInitializer(getvaluereal, PetscRandomGetValueReal_Rand),
41 };
42 
43 /*MC
44    PETSCRAND - access to the basic Unix random number generator
45 
46    Options Database Key:
47 . -random_type <rand,rand48,sprng> - set the random number generator from the options database
48 
49   Level: beginner
50 
51   Note:
52   Not recommended since it can produce different numbers on different systems
53 
54 .seealso: `PetscRandomCreate()`, `PetscRandomSetType()`, `PETSCRAND48`, `PETSCSPRNG`, `PetscRandomSetFromOptions()`, `PetscRandomType`
55 M*/
56 
57 PETSC_EXTERN PetscErrorCode PetscRandomCreate_Rand(PetscRandom r)
58 {
59   PetscFunctionBegin;
60   r->ops[0] = PetscRandomOps_Values;
61   PetscCall(PetscObjectChangeTypeName((PetscObject)r, PETSCRAND));
62   PetscFunctionReturn(PETSC_SUCCESS);
63 }
64