xref: /petsc/src/sys/classes/random/impls/rand/rand.c (revision f97672e55eacc8688507b9471cd7ec2664d7f203)
1 
2 #include <petsc/private/randomimpl.h>
3 
4 PetscErrorCode  PetscRandomSeed_Rand(PetscRandom r)
5 {
6   PetscFunctionBegin;
7   srand(r->seed);
8   PetscFunctionReturn(0);
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(0);
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(0);
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>
49 
50   Level: beginner
51 
52 .seealso: `PetscRandomCreate()`, `PetscRandomSetType()`, `PETSCRAND48`, `PETSCSPRNG`
53 M*/
54 
55 PETSC_EXTERN PetscErrorCode PetscRandomCreate_Rand(PetscRandom r)
56 {
57   PetscFunctionBegin;
58   PetscCall(PetscMemcpy(r->ops,&PetscRandomOps_Values,sizeof(PetscRandomOps_Values)));
59   PetscCall(PetscObjectChangeTypeName((PetscObject)r,PETSCRAND));
60   PetscFunctionReturn(0);
61 }
62