blob: ebe85ab69577eeb3c10e58de3eb73c1ab9e2457a [file] [log] [blame]
Austin Schuhdace2a62020-08-18 10:56:48 -07001/* mpf_urandomb (rop, state, nbits) -- Generate a uniform pseudorandom
2 real number between 0 (inclusive) and 1 (exclusive) of size NBITS,
3 using STATE as the random state previously initialized by a call to
4 gmp_randinit().
5
6Copyright 1999-2002 Free Software Foundation, Inc.
7
8This file is part of the GNU MP Library.
9
10The GNU MP Library is free software; you can redistribute it and/or modify
11it under the terms of either:
12
13 * the GNU Lesser General Public License as published by the Free
14 Software Foundation; either version 3 of the License, or (at your
15 option) any later version.
16
17or
18
19 * the GNU General Public License as published by the Free Software
20 Foundation; either version 2 of the License, or (at your option) any
21 later version.
22
23or both in parallel, as here.
24
25The GNU MP Library is distributed in the hope that it will be useful, but
26WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
27or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
28for more details.
29
30You should have received copies of the GNU General Public License and the
31GNU Lesser General Public License along with the GNU MP Library. If not,
32see https://www.gnu.org/licenses/. */
33
34#include "gmp-impl.h"
35
36void
37mpf_urandomb (mpf_t rop, gmp_randstate_t rstate, mp_bitcnt_t nbits)
38{
39 mp_ptr rp;
40 mp_size_t nlimbs;
41 mp_exp_t exp;
42 mp_size_t prec;
43
44 rp = PTR (rop);
45 nlimbs = BITS_TO_LIMBS (nbits);
46 prec = PREC (rop);
47
48 if (nlimbs > prec + 1 || nlimbs == 0)
49 {
50 nlimbs = prec + 1;
51 nbits = nlimbs * GMP_NUMB_BITS;
52 }
53
54 _gmp_rand (rp, rstate, nbits);
55
56 /* If nbits isn't a multiple of GMP_NUMB_BITS, shift up. */
57 if (nbits % GMP_NUMB_BITS != 0)
58 mpn_lshift (rp, rp, nlimbs, GMP_NUMB_BITS - nbits % GMP_NUMB_BITS);
59
60 exp = 0;
61 while (nlimbs != 0 && rp[nlimbs - 1] == 0)
62 {
63 nlimbs--;
64 exp--;
65 }
66 EXP (rop) = exp;
67 SIZ (rop) = nlimbs;
68}