xref: /petsc/src/sys/classes/random/impls/rand/rand.c (revision feff33ee0b5b037fa8f9f294dede656a2f85cc47)
1 
2 #include <../src/sys/classes/random/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   /* 0 */
40   PetscRandomSeed_Rand,
41   PetscRandomGetValue_Rand,
42   PetscRandomGetValueReal_Rand,
43   0,
44   /* 5 */
45   0
46 };
47 
48 /*MC
49    PETSCRAND - access to the basic Unix random number generator
50 
51    Options Database Keys:
52 . -random_type <rand,rand48,sprng>
53 
54   Level: beginner
55 
56 .seealso: RandomCreate(), RandomSetType(), PETSCRAND48, PETSCSPRNG
57 M*/
58 
59 PETSC_EXTERN PetscErrorCode PetscRandomCreate_Rand(PetscRandom r)
60 {
61   PetscErrorCode ierr;
62 
63   PetscFunctionBegin;
64   ierr = PetscMemcpy(r->ops,&PetscRandomOps_Values,sizeof(PetscRandomOps_Values));CHKERRQ(ierr);
65   ierr = PetscObjectChangeTypeName((PetscObject)r,PETSCRAND);CHKERRQ(ierr);
66   PetscFunctionReturn(0);
67 }
68