我总结两个负花车:GMP mpf_add的精度损失。我的数字在哪里?
char * lhs = "-2234.6016114467412141";
char * rhs = "-4939600281397002.2812";
据Perl中,使用BIGNUM和数学:: BigFloat,答案是
-4939600281399236.8828114467412141
然而,按GMP,使用下面的代码,答案是
-4939600281399236.88281
我哪里出错了?剩下的“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);
}
示例输出:
Using mpf_add, -2234.6016114467412141 + -4939600281397002.2812 = -493960028139923688281 (exp=16)
P.S.我曾尝试添加一个调用mpf_set_default_prec
大于64(默认值),但没有效果。
Spot on。我将宏改为 #define F(x)mpf_t(x); mpf_init2((x),128L); 和一切工作正常。 – bugmagnet 2009-01-21 09:47:08