2013-03-23 186 views
2

我只好用Python写的是一个更大的仿真的一部分,下面的功能:相同的功能,不同的结果

#!/usr/bin/python 
counter = 1 
while (counter < 10000): 
    oldpa = .5 
    t = 1 
    while (t < counter): 
     newpa = ((oldpa * t) + 1)/(t + 1) 
     t = t + 1 
     oldpa = newpa 
    counter = counter + 1 
    print str(counter) + "\t" + str(oldpa) 

然后,我开始用C重写模拟,以便它运行得更快(也给自己一个借口花时间学习C)。这是我的C版本的上述功能。

#include <stdio.h> 
main() 
{ 
    int counter, t; 
    float oldpa, newpa; 
    counter = 1; 
    while (counter < 10000) 
    { 
     oldpa = .5; 
     t = 1; 
     while (t < counter) 
     { 
      newpa = ((oldpa * t) + 1)/(t + 1); 
      t = t + 1; 
      oldpa = newpa; 
     } 
     counter = counter + 1; 
     printf("%d\t%f\n", counter, oldpa); 
    } 
} 

现在,这里是有趣的事情。当我运行Python函数时,结果收敛到0.999950,但是当我运行C函数时,它收敛到0.999883。这种差异对于我的模拟实际上可以忽略不计,但我仍然想知道为什么我会得到不同的结果

+2

c程序根本不适用于我,'counter + counter + 1;'是错误的。 – wRAR 2013-03-23 12:26:22

+2

[Here](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html)将是一个很好的开始。 – John 2013-03-23 12:26:45

+0

固定版本也收敛到0.999950。你使用的平台,编译器和编译器标志是什么? – wRAR 2013-03-23 12:27:21

回答