RandomLib  1.10
 All Classes Namespaces Files Functions Variables Typedefs Enumerator Friends Macros Pages
MPFRExample.cpp
Go to the documentation of this file.
1 /**
2  * \file MPFRExample.cpp
3  * \brief An example of calling RandomLib::MPFRNormal.
4  *
5  * Compile, link, and run with, e.g.,
6  * g++ -I../include -O2 -o MPFRExample MPFRExample.cpp -lmpfr -lgmp
7  * ./MPFRExample
8  *
9  * Copyright (c) Charles Karney (2012) <charles@karney.com> and licensed under
10  * the MIT/X11 License. For more information, see
11  * http://randomlib.sourceforge.net/
12  **********************************************************************/
13 
14 #include <cstdio>
15 #include <iostream>
16 #include <ctime> // for time()
17 #include <RandomLib/MPFRRandom.hpp>
18 #include <RandomLib/MPFRNormal.hpp>
19 
20 int main() {
21 #if HAVE_MPFR
22  gmp_randstate_t r;
23  gmp_randinit_mt(r);
24  time_t t0 = std::time(0);
25  gmp_randseed_ui(r, t0);
26  mpfr_t z;
27 
28  {
29  mpfr_prec_t prec = 240; mpfr_init2(z, prec);
30  std::cout << "Sample from the unit normal distribution at precision "
31  << prec << "\n";
32  RandomLib::MPFRNormal<> norm; // bits = 32, by default
33  for (int k = 0; k < 10; ++k) {
34  norm(z, r, MPFR_RNDN); // Obtain a normal deviate
35  mpfr_out_str(stdout, 10, 0, z, MPFR_RNDN); std::cout << "\n";
36  }
37  }
38 
39  {
40  mpfr_prec_t prec = 20; mpfr_set_prec(z, prec);
41  std::cout << "Sample ranges from the normal distribution at precision "
42  << prec << "\n";
43  RandomLib::MPFRNormal<1> norm; // choose bits = 1 so that the ranges
44  RandomLib::MPFRRandom<1> x; // are not too narrow
45  for (int k = 0; k < 10; ++k) {
46  norm(x, r); // Obtain an MPFRRandom range
47  x(z, MPFR_RNDD); // Lower bound of range
48  std::cout << "[" << mpfr_get_d(z, MPFR_RNDD) << ",";
49  x(z, MPFR_RNDU); // Upper bound of range
50  std::cout << mpfr_get_d(z, MPFR_RNDU) << "] -> ";
51  x(z, r, MPFR_RNDN); // Realize the normal deviate
52  mpfr_out_str(stdout, 10, 0, z, MPFR_RNDN); std::cout << "\n";
53  }
54  }
55 
56  // Clean up
57  mpfr_clear(z); mpfr_free_cache(); gmp_randclear(r);
58  return 0;
59 #else
60  std::cerr << "Need MPFR version 3.0 or later to run MPFRExample\n";
61  return 1;
62 #endif // HAVE_MPFR
63 }
int main()
Definition: MPFRExample.cpp:20
Header for MPFRNormal.
Handling random numbers in MPFR.
Definition: MPFRRandom.hpp:52
Header for MPFRRandom.
The normal distribution for MPFR.
Definition: MPFRNormal.hpp:33