2 years ago

#39045

test-img

Arc

A limitation in the eval mechanism of gmpxx in GMP?

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?

c++

eval

gmp

0 Answers

Your Answer

Accepted video resources