Actual source code: rand.c
1: #include <petsc/private/randomimpl.h>
3: static PetscErrorCode PetscRandomSeed_Rand(PetscRandom r)
4: {
5: PetscFunctionBegin;
6: srand(r->seed);
7: PetscFunctionReturn(PETSC_SUCCESS);
8: }
10: #define RAND_WRAP ((PetscReal)((rand() / (double)((unsigned int)RAND_MAX + 1))))
11: static PetscErrorCode PetscRandomGetValue_Rand(PetscRandom r, PetscScalar *val)
12: {
13: PetscFunctionBegin;
14: #if defined(PETSC_USE_COMPLEX)
15: if (r->iset) *val = PetscRealPart(r->width) * RAND_WRAP + PetscRealPart(r->low) + (PetscImaginaryPart(r->width) * RAND_WRAP + PetscImaginaryPart(r->low)) * PETSC_i;
16: else *val = RAND_WRAP + RAND_WRAP * PETSC_i;
17: #else
18: if (r->iset) *val = r->width * RAND_WRAP + r->low;
19: else *val = RAND_WRAP;
20: #endif
21: PetscFunctionReturn(PETSC_SUCCESS);
22: }
24: static PetscErrorCode PetscRandomGetValueReal_Rand(PetscRandom r, PetscReal *val)
25: {
26: PetscFunctionBegin;
27: #if defined(PETSC_USE_COMPLEX)
28: if (r->iset) *val = PetscRealPart(r->width) * RAND_WRAP + PetscRealPart(r->low);
29: else *val = RAND_WRAP;
30: #else
31: if (r->iset) *val = r->width * RAND_WRAP + r->low;
32: else *val = RAND_WRAP;
33: #endif
34: PetscFunctionReturn(PETSC_SUCCESS);
35: }
37: static struct _PetscRandomOps PetscRandomOps_Values = {
38: PetscDesignatedInitializer(seed, PetscRandomSeed_Rand),
39: PetscDesignatedInitializer(getvalue, PetscRandomGetValue_Rand),
40: PetscDesignatedInitializer(getvaluereal, PetscRandomGetValueReal_Rand),
41: };
43: /*MC
44: PETSCRAND - access to the basic Unix random number generator
46: Options Database Key:
47: . -random_type <rand,rand48,sprng> - set the random number generator from the options database
49: Level: beginner
51: Note:
52: Not recommended since it can produce different numbers on different systems
54: .seealso: `PetscRandomCreate()`, `PetscRandomSetType()`, `PETSCRAND48`, `PETSCSPRNG`, `PetscRandomSetFromOptions()`, `PetscRandomType`
55: M*/
57: PETSC_EXTERN PetscErrorCode PetscRandomCreate_Rand(PetscRandom r)
58: {
59: PetscFunctionBegin;
60: r->ops[0] = PetscRandomOps_Values;
61: PetscCall(PetscObjectChangeTypeName((PetscObject)r, PETSCRAND));
62: PetscFunctionReturn(PETSC_SUCCESS);
63: }