怎么可能C算术如此不精确?

时间:2011-05-12 21:21:16

标签: c math loops

  

可能重复:
  Floating point inaccuracy examples

在我的电脑上使用g ++我发现:

21*3.6 ==  75.60000000000000852651

这会破坏一个简单的循环。看到这段代码:

  double incr=3.6;
  double limit=21*3.6;
  printf (" ¿%f == %.20f? \n", limit, limit);
  for (double x=0.0; x<limit; x += incr) {
    printf (" x %f < limit %f (dif = %.20f) \n", x, limit, limit-x);
  }

及其输出:

 ¿75.600000 == 75.60000000000000852651? 
x=0.000000, limit=75.600000 (dif = 75.60000000000000852651) 
x=3.600000, limit=75.600000 (dif = 72.00000000000001421085) 
x=7.200000, limit=75.600000 (dif = 68.40000000000000568434) 
x=10.800000, limit=75.600000 (dif = 64.80000000000001136868) 
x=14.400000, limit=75.600000 (dif = 61.20000000000000994760) 
x=18.000000, limit=75.600000 (dif = 57.60000000000000852651) 
x=21.600000, limit=75.600000 (dif = 54.00000000000000710543) 
x=25.200000, limit=75.600000 (dif = 50.40000000000000568434) 
x=28.800000, limit=75.600000 (dif = 46.80000000000000426326) 
x=32.400000, limit=75.600000 (dif = 43.20000000000000284217) 
x=36.000000, limit=75.600000 (dif = 39.60000000000000142109) 
x=39.600000, limit=75.600000 (dif = 36.00000000000000000000) 
x=43.200000, limit=75.600000 (dif = 32.39999999999999857891) 
x=46.800000, limit=75.600000 (dif = 28.79999999999999715783) 
x=50.400000, limit=75.600000 (dif = 25.19999999999999573674) 
x=54.000000, limit=75.600000 (dif = 21.59999999999999431566) 
x=57.600000, limit=75.600000 (dif = 17.99999999999999289457) 
x=61.200000, limit=75.600000 (dif = 14.39999999999999147349) 
x=64.800000, limit=75.600000 (dif = 10.79999999999999715783) 
x=68.400000, limit=75.600000 (dif = 7.20000000000000284217) 
x=72.000000, limit=75.600000 (dif = 3.60000000000000852651) 
x=75.600000, limit=75.600000 (dif = 0.00000000000001421085)  

表示上一次不应该执行循环 但是对于错误!

建议?

1 个答案:

答案 0 :(得分:6)

你需要阅读:

What Every Computer Scientist Should Know About Floating-Point Arithmetic

您正在使用浮点数,您需要知道浮点数的含义。它能做什么,不能做什么。有些数字可以用几位数的文本表示,不能用定点或浮点二进制数字形式精确表示。您正在假设浮点不仅与C编程有关,而是与使用浮点数的任何计算机系统有关。