xref: /petsc/src/sys/classes/random/impls/rand/rand.c (revision 9371c9d470a9602b6d10a8bf50c9b2280a79e45a)
1 
2 #include <petsc/private/randomimpl.h>
3 
4 PetscErrorCode PetscRandomSeed_Rand(PetscRandom r) {
5   PetscFunctionBegin;
6   srand(r->seed);
7   PetscFunctionReturn(0);
8 }
9 
10 #define RAND_WRAP ((PetscReal)((rand() / (double)((unsigned int)RAND_MAX + 1))))
11 PetscErrorCode PetscRandomGetValue_Rand(PetscRandom r, PetscScalar *val) {
12   PetscFunctionBegin;
13 #if defined(PETSC_USE_COMPLEX)
14   if (r->iset) *val = PetscRealPart(r->width) * RAND_WRAP + PetscRealPart(r->low) + (PetscImaginaryPart(r->width) * RAND_WRAP + PetscImaginaryPart(r->low)) * PETSC_i;
15   else *val = RAND_WRAP + RAND_WRAP * PETSC_i;
16 #else
17   if (r->iset) *val = r->width * RAND_WRAP + r->low;
18   else *val = RAND_WRAP;
19 #endif
20   PetscFunctionReturn(0);
21 }
22 
23 PetscErrorCode PetscRandomGetValueReal_Rand(PetscRandom r, PetscReal *val) {
24   PetscFunctionBegin;
25 #if defined(PETSC_USE_COMPLEX)
26   if (r->iset) *val = PetscRealPart(r->width) * RAND_WRAP + PetscRealPart(r->low);
27   else *val = RAND_WRAP;
28 #else
29   if (r->iset) *val = r->width * RAND_WRAP + r->low;
30   else *val = RAND_WRAP;
31 #endif
32   PetscFunctionReturn(0);
33 }
34 
35 static struct _PetscRandomOps PetscRandomOps_Values = {
36   PetscDesignatedInitializer(seed, PetscRandomSeed_Rand),
37   PetscDesignatedInitializer(getvalue, PetscRandomGetValue_Rand),
38   PetscDesignatedInitializer(getvaluereal, PetscRandomGetValueReal_Rand),
39 };
40 
41 /*MC
42    PETSCRAND - access to the basic Unix random number generator
43 
44    Options Database Keys:
45 . -random_type <rand,rand48,sprng> - set the random number generator from the options database
46 
47   Level: beginner
48 
49 .seealso: `PetscRandomCreate()`, `PetscRandomSetType()`, `PETSCRAND48`, `PETSCSPRNG`, `PetscRandomSetFromOptions()`
50 M*/
51 
52 PETSC_EXTERN PetscErrorCode PetscRandomCreate_Rand(PetscRandom r) {
53   PetscFunctionBegin;
54   PetscCall(PetscMemcpy(r->ops, &PetscRandomOps_Values, sizeof(PetscRandomOps_Values)));
55   PetscCall(PetscObjectChangeTypeName((PetscObject)r, PETSCRAND));
56   PetscFunctionReturn(0);
57 }
58