github.com/aergoio/aergo@v1.3.1/libtool/src/gmp-6.1.2/mpf/urandomb.c (about)

     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.h"
    35  #include "gmp-impl.h"
    36  
    37  void
    38  mpf_urandomb (mpf_t rop, gmp_randstate_t rstate, mp_bitcnt_t nbits)
    39  {
    40    mp_ptr rp;
    41    mp_size_t nlimbs;
    42    mp_exp_t exp;
    43    mp_size_t prec;
    44  
    45    rp = PTR (rop);
    46    nlimbs = BITS_TO_LIMBS (nbits);
    47    prec = PREC (rop);
    48  
    49    if (nlimbs > prec + 1 || nlimbs == 0)
    50      {
    51        nlimbs = prec + 1;
    52        nbits = nlimbs * GMP_NUMB_BITS;
    53      }
    54  
    55    _gmp_rand (rp, rstate, nbits);
    56  
    57    /* If nbits isn't a multiple of GMP_NUMB_BITS, shift up.  */
    58    if (nbits % GMP_NUMB_BITS != 0)
    59      mpn_lshift (rp, rp, nlimbs, GMP_NUMB_BITS - nbits % GMP_NUMB_BITS);
    60  
    61    exp = 0;
    62    while (nlimbs != 0 && rp[nlimbs - 1] == 0)
    63      {
    64        nlimbs--;
    65        exp--;
    66      }
    67    EXP (rop) = exp;
    68    SIZ (rop) = nlimbs;
    69  }