Austin Schuh | dace2a6 | 2020-08-18 10:56:48 -0700 | [diff] [blame] | 1 | /* 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 | |
| 6 | Copyright 1999-2002 Free Software Foundation, Inc. |
| 7 | |
| 8 | This file is part of the GNU MP Library. |
| 9 | |
| 10 | The GNU MP Library is free software; you can redistribute it and/or modify |
| 11 | it 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 | |
| 17 | or |
| 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 | |
| 23 | or both in parallel, as here. |
| 24 | |
| 25 | The GNU MP Library is distributed in the hope that it will be useful, but |
| 26 | WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY |
| 27 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
| 28 | for more details. |
| 29 | |
| 30 | You should have received copies of the GNU General Public License and the |
| 31 | GNU Lesser General Public License along with the GNU MP Library. If not, |
| 32 | see https://www.gnu.org/licenses/. */ |
| 33 | |
| 34 | #include "gmp-impl.h" |
| 35 | |
| 36 | void |
| 37 | mpf_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 | } |