Skip to content

Commit

Permalink
Merge pull request #260 from qxzkjp/master
Browse files Browse the repository at this point in the history
Added get_randstate_t method to gmp_randclass
  • Loading branch information
wbhart committed Sep 20, 2018
2 parents 6bb6433 + 9e3b206 commit 1cc83d5
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 0 deletions.
12 changes: 12 additions & 0 deletions doc/mpir.texi
Expand Up @@ -6849,6 +6849,18 @@ f = r.get_f(); // random number, 512 bits
@end example
@end deftypefun

@deftypefun randstate_t gmp_randclass::get_randstate_t ()
Get the underlying @code{randstate_t} from the object. This can be used to call a
C function that doesn't have a C++ interface. For example, to check if an integer
is prime,
@example
gmp_randclass r(gmp_randinit_mt);
mpz_class p;
// ... seed r and generate p ...
is_prime = mpz_likely_prime_p(p.get_mpz_t(), r.get_randstate_t(), 0);
@end example
@end deftypefun



@node C++ Interface Limitations, , C++ Interface Random Numbers, C++ Class Interface
Expand Down
2 changes: 2 additions & 0 deletions gmp-h.in
Expand Up @@ -314,6 +314,8 @@ typedef __gmp_const __mpf_struct *mpf_srcptr;
typedef __mpf_struct *mpf_ptr;
typedef __gmp_const __mpq_struct *mpq_srcptr;
typedef __mpq_struct *mpq_ptr;
typedef __gmp_const __gmp_randstate_struct *randstate_srcptr;
typedef __gmp_randstate_struct *randstate_ptr;


#if __GMP_LIBGMP_DLL
Expand Down
4 changes: 4 additions & 0 deletions mpirxx.h
Expand Up @@ -3482,6 +3482,10 @@ class gmp_randclass
void seed(mpir_ui s) { gmp_randseed_ui(state, s); }
void seed(const mpz_class &z) { gmp_randseed(state, z.get_mpz_t()); }

//get randstate_t for compatibility with non-OO API functions
randstate_srcptr get_randstate_t() const { return this->state; }
randstate_ptr get_randstate_t() { return this->state; }

// get random number
__gmp_expr<mpz_t, __gmp_urandomb_value> get_z_bits(mp_bitcnt_t l)
{ return __gmp_expr<mpz_t, __gmp_urandomb_value>(state, l); }
Expand Down
26 changes: 26 additions & 0 deletions tests/cxx/t-rand.cc
Expand Up @@ -126,6 +126,31 @@ check_mpf (void)
}
}

/*check that get_randstate_t really returns the randstate_t underlying a gmp_randclass*/
void
check_randstate_t(void)
{
/*seed gmp_randclass r using its method, and seed gmp_randclass s using get_randstate_t
if they both generate the same sequence, then gmp_randstate_t must be returning the
underlying randstate_t of s */
{
gmp_randclass r(gmp_randinit_default);
gmp_randclass s(gmp_randinit_default);
__gmp_randstate_struct s_state = *s.get_randstate_t();

r.seed(0xdeadbeef);
gmp_randseed_ui(&s_state, 0xdeadbeef);

bool res = true;
for (int i = 0; i < 100; ++i)
{
mpz_class n1 = r.get_z_bits(32);
mpz_class n2 = s.get_z_bits(32);
ASSERT_ALWAYS (n1 == n2);
}
}
}


int
main (void)
Expand All @@ -135,6 +160,7 @@ main (void)
check_randinit();
check_mpz();
check_mpf();
check_randstate_t();

tests_end();
return 0;
Expand Down

0 comments on commit 1cc83d5

Please sign in to comment.