xref: /petsc/src/sys/classes/random/impls/rand/rand.c (revision 2fa5cd679192b9b390e47ae2d0650965e6b1d9fa)
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) *val = PetscRealPart(r->width)*RAND_WRAP + PetscRealPart(r->low) + (PetscImaginaryPart(r->width)*RAND_WRAP + PetscImaginaryPart(r->low)) * PETSC_i;
24   else *val = RAND_WRAP + RAND_WRAP*PETSC_i;
25 #else
26   if (r->iset) *val = r->width * RAND_WRAP + r->low;
27   else         *val = RAND_WRAP;
28 #endif
29   PetscFunctionReturn(0);
30 }
31 
32 #undef __FUNCT__
33 #define __FUNCT__ "PetscRandomGetValueReal_Rand"
34 PetscErrorCode  PetscRandomGetValueReal_Rand(PetscRandom r,PetscReal *val)
35 {
36   PetscFunctionBegin;
37 #if defined(PETSC_USE_COMPLEX)
38     if (r->iset) *val = PetscRealPart(r->width)*RAND_WRAP + PetscRealPart(r->low);
39     else         *val = RAND_WRAP;
40 #else
41   if (r->iset) *val = r->width * RAND_WRAP + r->low;
42   else         *val = RAND_WRAP;
43 #endif
44   PetscFunctionReturn(0);
45 }
46 
47 static struct _PetscRandomOps PetscRandomOps_Values = {
48   /* 0 */
49   PetscRandomSeed_Rand,
50   PetscRandomGetValue_Rand,
51   PetscRandomGetValueReal_Rand,
52   0,
53   /* 5 */
54   0
55 };
56 
57 /*MC
58    PETSCRAND - access to the basic Unix random number generator
59 
60    Options Database Keys:
61 . -random_type <rand,rand48,sprng>
62 
63   Level: beginner
64 
65 .seealso: RandomCreate(), RandomSetType(), PETSCRAND48, PETSCSPRNG
66 M*/
67 
68 EXTERN_C_BEGIN
69 #undef __FUNCT__
70 #define __FUNCT__ "PetscRandomCreate_Rand"
71 PetscErrorCode  PetscRandomCreate_Rand(PetscRandom r)
72 {
73   PetscErrorCode ierr;
74 
75   PetscFunctionBegin;
76   ierr = PetscMemcpy(r->ops,&PetscRandomOps_Values,sizeof(PetscRandomOps_Values));CHKERRQ(ierr);
77   ierr = PetscObjectChangeTypeName((PetscObject)r,PETSCRAND);CHKERRQ(ierr);
78   PetscFunctionReturn(0);
79 }
80 EXTERN_C_END
81