GMP 的精度损失

Precision loss with GMP

我有一个程序可以将字符串中的数字读取为 mpz_t,然后将其转换为 mpf_t。尽管可以从文件中正确读取,但当我将它们转换为 mpf_t 时,精度会有所损失。代码如下:

#include <gmp.h>
#include <stdlib.h>
#include <stdio.h>

int main (int argc, char **argv) {
    char* str = "632512364206354367378453";
    mpz_t x;

    mpz_init_set_str(x, str, 10);

    mpf_t a;
    mpf_init(a);
    mpf_set_z(a, x);
    gmp_printf("mpz_t: %Zd\n", x);
    gmp_printf("mpf_t: %Ff\n", a);
}

这个例子的输出是:

mpz_t: 632512364206354367378453
mpf_t: 632512364206354367378000.000000

如您所见,最后 3 位数字不正确。我怎样才能避免这种情况?还有其他函数可以执行此转换吗?

谢谢

来自manual page

Function: void mpf_init (mpf_t x)

Initialize x to 0. Normally, a variable should be initialized once only or at least be cleared, using mpf_clear, between initializations. The precision of x is undefined unless a default precision has already been established by a call to mpf_set_default_prec.

这是你的问题。

解决方案:

Function: void mpf_init2 (mpf_t x, mp_bitcnt_t prec)

Initialize x to 0 and set its precision to be at least prec bits. Normally, a variable should be initialized once only or at least be cleared, using mpf_clear, between initializations.

这样,您可以使用 prec 精度计数参数来指定您想要的精度位数。