Lost precision on GMP mpf_add. Where have my digits gone?

雨燕双飞 提交于 2020-01-15 01:52:24

问题


I'm summing two negative floats:

char * lhs = "-2234.6016114467412141";
char * rhs = "-4939600281397002.2812";

According to Perl, using bignum and Math::BigFloat, the answer is

-4939600281399236.8828114467412141

However, according to GMP, using the code below, the answer is

-4939600281399236.88281 

Where have I gone wrong? What happened to the remaining "14467412141"?

#include "stdafx.h"
#include "gmp-static\gmp.h"
#include <stdlib.h>         /* For _MAX_PATH definition */
#include <stdio.h>
#include <malloc.h>
#include <math.h>

#define F(x) mpf_t x; mpf_init( x );

void main(void)
{
    F(f_lhs);
    F(f_rhs);
    F(f_res);

    char * resbuff;

    mp_exp_t exp;

    char * lhs = "-2234.6016114467412141";
    char * rhs = "-4939600281397002.2812";

    int validOp = mpf_set_str( f_lhs, lhs, 10 );
    validOp = mpf_set_str( f_rhs, rhs, 10 );

    mpf_add( f_res, f_lhs, f_rhs );

    resbuff = mpf_get_str( NULL, &exp, 10, 0, f_res );
    printf( "Using mpf_add, %s + %s = %s (exp=%d)\n", lhs, rhs, resbuff, exp );

    free(resbuff);
}

Sample output:

Using mpf_add, -2234.6016114467412141 + -4939600281397002.2812 = -493960028139923688281 (exp=16)

P.S. I have tried adding a call to mpf_set_default_prec with larger than 64 (the default) values, but to no effect.


回答1:


Looks like you are overflowing the mantissa at 64 bits. Try doing mpf_get_prec(f_res) to check it is the precision you want. If not call the mpf_set_default_prec() before you initialize any mpf vars (line 1 of main).




回答2:


Boot with a larger value. Try this:

mpf_set_default_prec(5*1024)


来源:https://stackoverflow.com/questions/464358/lost-precision-on-gmp-mpf-add-where-have-my-digits-gone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!