Search code examples
c++fstreammpfr

Print to file from MPFR


I want to print the result of a calculation using MPFR to file but I don't know how. MPFR is used to do floating point operations with high accuracy. To print an mpfr_t number you use the function:

size_t mpfr_out_str (FILE *stream, int base, size t n, mpfr t op, mp rnd t rnd)

I guess my problem is that I don't understand FILE* objects and how they are related to fstream objects.

If I change my_file in the mpfr_out_str line to stdout then the number will print to the screen as I'd hoped but I don't know how to get it into the file.

#include <mpfr.h>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
   mpfr_t x;
   mpfr_init(x);
   mpfr_set_d(x, 1, MPFR_RNDN);

   ofstream my_file;
   my_file.open("output.txt");
   mpfr_out_str(my_file, 2, 0, x, MPFR_RNDN);
   my_file.close();
}

Solution

  • It is possible to use the std::ostream methods with mpfr functions like mpfr_as_printf or mpfr_get_str. It however requires an additional string allocation.

      #include <mpfr.h>
      #include <iostream>
      #include <fstream>
      using namespace std;
      int main() {
         mpfr_t x;
         mpfr_init(x);
         mpfr_set_d(x, 1, MPFR_RNDN);
    
         ofstream my_file;
         my_file.open("output.txt");
    
         char* outString = NULL;
         mpfr_asprintf(&outString, "%RNb", x);
         my_file << outString;
         mpfr_free_str(outString);
         my_file.close();
    
         mpfr_clear(x);
      }