Actual source code: rand.c
2: #include <petsc/private/randomimpl.h>
4: PetscErrorCode PetscRandomSeed_Rand(PetscRandom r)
5: {
6: PetscFunctionBegin;
7: srand(r->seed);
8: PetscFunctionReturn(PETSC_SUCCESS);
9: }
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(PETSC_SUCCESS);
23: }
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(PETSC_SUCCESS);
36: }
38: static struct _PetscRandomOps PetscRandomOps_Values = {
39: PetscDesignatedInitializer(seed, PetscRandomSeed_Rand),
40: PetscDesignatedInitializer(getvalue, PetscRandomGetValue_Rand),
41: PetscDesignatedInitializer(getvaluereal, PetscRandomGetValueReal_Rand),
42: };
44: /*MC
45: PETSCRAND - access to the basic Unix random number generator
47: Options Database Keys:
48: . -random_type <rand,rand48,sprng> - set the random number generator from the options database
50: Level: beginner
52: Note:
53: Not recommended since it can produce different numbers on different systems
55: .seealso: `PetscRandomCreate()`, `PetscRandomSetType()`, `PETSCRAND48`, `PETSCSPRNG`, `PetscRandomSetFromOptions()`, `PetscRandomType`
56: M*/
58: PETSC_EXTERN PetscErrorCode PetscRandomCreate_Rand(PetscRandom r)
59: {
60: PetscFunctionBegin;
61: PetscCall(PetscMemcpy(r->ops, &PetscRandomOps_Values, sizeof(PetscRandomOps_Values)));
62: PetscCall(PetscObjectChangeTypeName((PetscObject)r, PETSCRAND));
63: PetscFunctionReturn(PETSC_SUCCESS);
64: }