在C中乘以Doubles时会失去精度 [英] Losing precision when multiplying Doubles in C

查看:79
本文介绍了在C中乘以Doubles时会失去精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取大约500倍的双数的多重小数部分.随着时间的流逝,这个数字开始失去精度.有什么技巧可以使连续乘法准确吗?

I am trying to get multiplay decimal part of a double number about 500 times. This number starts to lose precision as time goes on. Is there any trick to be able to make the continued multiplication accurate?

double x = 0.3;
double binary = 2.0;

for (i=0; i<500; i++){
    x = x * binary;
    printf("x equals to : %f",x);
    if(x>=1.0)
        x = x - 1;
}

好,在我阅读了您发布的一些内容之后,我在想如何才能从我的数字中删除这些不需要的内容,以保持乘法稳定.例如在我的例子中.我的小数部分将以这种方式更改:0.3,0.6,0.2,0.4,0.8...我们可以削减其余部分以保留此数字吗?

Ok after i read some of the things u posted i am thinking how could i remove this unwanted stuff from my number to keep multiplication stable. For instance in my example. My decimal parts will be chaning in such manner: 0.3,0.6,0.2,0.4,0.8... Can we cut the rest to keep this numbers ??

推荐答案

典型的FP是 binary64 double x = 0.3;导致x的值更像0.29999999999999998890...,因此代码与开始时有所不同.

With typical FP is binary64, double x = 0.3; results in x with the value more like 0.29999999999999998890... so code has an difference from the beginning.

x缩放10以保持精确的数学-或使用 decimal64

Scale x by 10 to stay with exact math - or use a decimal64 double

int main(void) {
  double x = 3.0;
  double binary = 2.0;
  printf("x equals to : %.20f\n",x);
  for (int i=0; i<500; i++){
      x = x * binary;
      printf("x equals to : %.20f\n",x/10);
      if(x>=10.0)
          x = x - 10;
  }
  return 0;
}

这篇关于在C中乘以Doubles时会失去精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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