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