emacs drives me nuts
emacs drives me nuts

Reputation: 3888

MPFR: How to make an exact copy of mpfr_t?

I am just stuck with how to make an exact copy of mpfr_t with MPFR 3.1.4: Same precision, exact same value, no rounding.

void copy (mpfr_t x)
{
    mpfr_t y;
    mpfr_init2 (y, mpfr_get_prec (x));
    // Bummer: mpfr_set will round.
}

Upvotes: 0

Views: 339

Answers (1)

vinc17
vinc17

Reputation: 3371

The best way is to use mpfr_set after setting the precision as you did. There will be no rounding, or if you prefer, the rounding operation will not modify the value. If the value is NaN, its sign bit will not be copied, but you probably don't care (and if you really care, you can still copy the sign bit with mpfr_copysign).

Do not copy the mpfr_t with memcpy or something similar. You'll get the same value after this copy, but the significand will be shared by both numbers (since one field is a pointer to the significand), and modifying one of these numbers will modify the other one, and you'll get an even more erratic behavior (possible crash...) in case the number changes to a special value (NaN, ±Inf, ±0) or its precision is changed.

Upvotes: 1

Related Questions