用gmp添加浮游物给“正确的”结果,有点 [英] Adding floats with gmp gives "correct" results, sort of

查看:207
本文介绍了用gmp添加浮游物给“正确的”结果,有点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我使用 mpf_add 来添加两个浮点值的字符串表示。我现在不明白的是为什么 2.2 + 3.2 = 5.39999999999999999999999999999999999999 。我原以为 gmp 足够聪明,给 5.4

我不理解gmp是如何浮动的?

(顺便说一句,当我第一次写这个I不知道如何插入一个小数点,因此在最后加/减数字的东西)

$ pre $ BS $ __stdcall FBIGSUM( BSTR p1,BSTR p2){
USES_CONVERSION;

F(n1);
F(n2);
F(res);

LPSTR sNum1 = W2A(p1);
LPSTR sNum2 = W2A(p2);

mpf_set_str(n1,sNum1,10);
mpf_set_str(n2,sNum2,10);

mpf_add(res,n1,n2);

char * buff =(char *)_alloca(1024);
char expBuffer [20];
mp_exp_t exp;

mpf_get_str(buff,& exp,10,0,res);
$ b $ char * temp = ltoa((long)exp,expBuffer,10);
if(exp> = 0){
strcat(buff,+);
}
strcat(buff,expBuffer);

BSTR bResult = _com_util :: ConvertStringToBSTR(buff);
返回bResult;


解决方案

在二进制环境中使用浮点运算的错误。



请参阅 IEEE 754 标准的更多信息。

In the code below I use mpf_add to add the string representation of two floating values. What I don't understand at this point is why 2.2 + 3.2 = 5.39999999999999999999999999999999999999. I would have thought that gmp was smart enough to give 5.4.

What am I not comprehending about how gmp does floats?

(BTW, when I first wrote this I wasn't sure how to insert a decimal point, thus the plus/minus digit stuff at the end)

BSTR __stdcall FBIGSUM(BSTR p1, BSTR p2 ) {
  USES_CONVERSION;

  F(n1);
  F(n2);
  F(res);

  LPSTR sNum1 = W2A( p1 );
  LPSTR sNum2 = W2A( p2 );

  mpf_set_str( n1, sNum1, 10 );
  mpf_set_str( n2, sNum2, 10 );

  mpf_add( res, n1, n2 );

  char * buff =  (char *) _alloca( 1024 );
  char expBuffer[ 20 ];
  mp_exp_t exp;

  mpf_get_str(buff, &exp, 10, 0, res);

  char * temp = ltoa( (long) exp, expBuffer, 10 );
  if (exp >= 0) {
    strcat(buff, "+" );
  }
  strcat(buff, expBuffer );

  BSTR bResult = _com_util::ConvertStringToBSTR( buff );
  return bResult;
}

解决方案

This is because of the inherent error of using floating-point arithmetic in a binary environment.

See the IEEE 754 standard for more information.

这篇关于用gmp添加浮游物给“正确的”结果,有点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆