2013-03-23 183 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

回答