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