0
$\begingroup$

In PETSc, I need to generate a random number between 1 and 0.

With the include cstdlib, the classical trick is:

(double)rand() / (double)RAND_MAX

In PETSc, the constant RAND_MAX does not seem to exist.

Is there a work around?

Though it is ugly, I plan to do something similar to:

(rand() % 10000) / 10000.0
$\endgroup$
  • 1
    $\begingroup$ You may want to use another library, like SPRNG $\endgroup$ – Paul Mar 18 '16 at 19:17
1
$\begingroup$

To elaborate somewhat on Paul's point, generating pseudo-random numbers in parallel requires some amount of care. Usually, when you generate PRNs, you seed the generator with something like the system time down to the millisecond. However, if you do this in a parallel program, you may well seed the generator with the same time on every process, giving you the same pseudo-random sequence on each processor.

PETSc does have a function PetscRandomCreate, but the documentation for it even admonishes you that

...it should NOT be used for sophisticated parallel Monte Carlo methods since it will very likely not have the correct statistics across processors.

You can decide for yourself whether this caveat will apply to your case. Either way, it's always a good idea to use something like a QQ plot to check that the random numbers you're generating have the distribution that you think they do.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.