开发者

floating point rounding errors

The output is

x=1000300  y=1000000,  z=1000300

I can understand how I got x and z but c's y's output makes no sense.

 #i开发者_如何学Pythonnclude <stdio.h> 
 int main() 
 { int i=0; 
  float a = 100; 
  a = a*a*a*a*a;  

 float c = 3; 
 float x = 1000000*c + a; 
 float y = a; 
 float z = 0; 

  for (i=0; i<1000000; i++) 
  { y += c; 
    z += c; 
  } 

  z += a; 
  x /= 10000; 
  y /= 10000; 
  z /= 10000; 

 printf("x=%.0f  y=%.0f,  z=%.0f\n", x, y, z); 
 }


The value in y starts out at 1E10 (from the assignment to a). You add 3 to this a million times.

The trouble is that a float has at most 7 significant decimal digits, so you effectively do not change y each time, hence the result divided by 10,000 is 10,000,000 1,000,000 as displayed.

If you coded it with double, you would see more nearly the result you expect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜