xref: /petsc/src/sys/classes/random/impls/rand/rand.c (revision 3e1910f1ab6113d8365e15c6b8c907ccce7ce4ea)
1 
2 #include <../src/sys/classes/random/randomimpl.h>
3 
4 #undef __FUNCT__
5 #define __FUNCT__ "PetscRandomSeed_Rand"
6 PetscErrorCode  PetscRandomSeed_Rand(PetscRandom r)
7 {
8   PetscFunctionBegin;
9   srand(r->seed);
10   PetscFunctionReturn(0);
11 }
12 
13 #define RAND_WRAP ((PetscReal)((rand()/(double)((unsigned int)RAND_MAX+1))))
14 #undef __FUNCT__
15 #define __FUNCT__ "PetscRandomGetValue_Rand"
16 PetscErrorCode  PetscRandomGetValue_Rand(PetscRandom r,PetscScalar *val)
17 {
18   PetscFunctionBegin;
19 #if defined(PETSC_USE_COMPLEX)
20   if (r->iset) *val = PetscRealPart(r->width)*RAND_WRAP + PetscRealPart(r->low) + (PetscImaginaryPart(r->width)*RAND_WRAP + PetscImaginaryPart(r->low)) * PETSC_i;
21   else *val = RAND_WRAP + RAND_WRAP*PETSC_i;
22 #else
23   if (r->iset) *val = r->width * RAND_WRAP + r->low;
24   else         *val = RAND_WRAP;
25 #endif
26   PetscFunctionReturn(0);
27 }
28 
29 #undef __FUNCT__
30 #define __FUNCT__ "PetscRandomGetValueReal_Rand"
31 PetscErrorCode  PetscRandomGetValueReal_Rand(PetscRandom r,PetscReal *val)
32 {
33   PetscFunctionBegin;
34 #if defined(PETSC_USE_COMPLEX)
35     if (r->iset) *val = PetscRealPart(r->width)*RAND_WRAP + PetscRealPart(r->low);
36     else         *val = RAND_WRAP;
37 #else
38   if (r->iset) *val = r->width * RAND_WRAP + r->low;
39   else         *val = RAND_WRAP;
40 #endif
41   PetscFunctionReturn(0);
42 }
43 
44 static struct _PetscRandomOps PetscRandomOps_Values = {
45   /* 0 */
46   PetscRandomSeed_Rand,
47   PetscRandomGetValue_Rand,
48   PetscRandomGetValueReal_Rand,
49   0,
50   /* 5 */
51   0
52 };
53 
54 /*MC
55    PETSCRAND - access to the basic Unix random number generator
56 
57    Options Database Keys:
58 . -random_type <rand,rand48,sprng>
59 
60   Level: beginner
61 
62 .seealso: RandomCreate(), RandomSetType(), PETSCRAND48, PETSCSPRNG
63 M*/
64 
65 #undef __FUNCT__
66 #define __FUNCT__ "PetscRandomCreate_Rand"
67 PETSC_EXTERN PetscErrorCode PetscRandomCreate_Rand(PetscRandom r)
68 {
69   PetscErrorCode ierr;
70 
71   PetscFunctionBegin;
72   ierr = PetscMemcpy(r->ops,&PetscRandomOps_Values,sizeof(PetscRandomOps_Values));CHKERRQ(ierr);
73   ierr = PetscObjectChangeTypeName((PetscObject)r,PETSCRAND);CHKERRQ(ierr);
74   PetscFunctionReturn(0);
75 }
76