GMP mpf_add 失去精度。 我的数字去哪儿了?
我对两个负浮点数求和:
char * lhs = "-2234.6016114467412141";
char * rhs = "-4939600281397002.2812";
根据 Perl,使用 bignum 和 Math::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)
PS 我尝试添加对大于 64(默认)值的 mpf_set_default_prec
的调用,但没有效果。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来 64 位的尾数溢出了。 尝试执行 mpf_get_prec(f_res) 来检查它是否是您想要的精度。 如果没有在初始化任何 mpf 变量(main 的第 1 行)之前调用 mpf_set_default_prec()。
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 thempf_set_default_prec()
before you initialize any mpf vars (line 1 of main).以较大的值启动。 尝试这个:
Boot with a larger value. Try this: