1

The GNU MP library provides a C++ interface in gmpxx.h which overloads arithmetic operators (among other functions), to make it easier for developers to write mathematical expressions using arbitrary-precision types, just like expressions that use native numerical types (see this answer).

While running code to write this answer, I came across an unexpected behaviour in how the interface handles expressions containing GMP types: passing a subtraction of mpf_t variables directly as an argument to gmp_printf gives the wrong answer, but saving the subtraction result into an intermediary variable works fine.

C++ code:

#include <iostream>
#include <gmpxx.h>
using namespace std;

int main (void) {
    mpf_class actual = 1. / 6;
    mpf_class expected("0.166666666666666666666666666666667");
    gmp_printf("diff %.50Ff\n", expected - actual);
    mpf_class diff = expected - actual;
    gmp_printf("diff %.50Ff\n", diff);
}

The output:

diff 0.16666666666666666666700000000000000000000000000000
diff 0.00000000000000000925185853854297150353000000000000

And, assuming the name testgmpxx.cpp, compile with:

g++ testgmpxx.cpp -o testgmpxx -lgmpxx -lgmp

Is this a limitation in the gmpxx.h eval mechanism? Are there are instances where you can't use GMP types on mathematical expressions?

Arc
  • 412
  • 2
  • 16
  • 2
    https://gmplib.org/manual/Formatted-Output-Strings says that 'F' is for mpf_t, not `mpf_class`. Since gmp_printf is a C variadic function, it is hard to print a diagnostic. The fact that the line with `diff` "works" is a random accident. – Marc Glisse Jan 11 '22 at 19:43
  • @MarcGlisse, probably it works because the `mpf_t` is the first data structure on the class, note that in printing `expected - actual` it only prints `expected`, which is the first term. Also, printing `(expected - actual).get_mpf_t()` doesn't work. I'm amazed that the `g++` compiler does not detect the incorrect class type, even if given the `-Wall` option. – Arc Jan 12 '22 at 00:36
  • @Arc: `printf`-like functions need special handling from the compiler to detect any such error, custom-written for each that doesn’t just forward the same format string to another. – Davis Herring Jan 12 '22 at 03:15
  • @DavisHerring, ok, understood, thanks, GMP is very powerful, but it has its particularities. – Arc Jan 12 '22 at 22:29
  • 1
    @MarcGlisse, do you want to add that as an answer? I think it solves the issue, and people might benefit more clearly from your answer advice. – Arc Jan 12 '22 at 22:30

0 Answers0