Python和C中的函数相同,结果不同

Python和C中的函数相同,结果不同,python,c,Python,C,作为更大模拟的一部分,我用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

作为更大模拟的一部分,我用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)
#/usr/bin/python
计数器=1
而(计数器<10000):
奥尔德帕=.5
t=1
而(t
然后,我开始用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);
   }
}
#包括
main()
{
int计数器,t;
浮动oldpa、newpa;
计数器=1;
同时(计数器<10000)
{
oldpa=0.5;
t=1;
while(t

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

< Python中的浮点值几乎总是IEEE-75,对应于C或C++ +COD>双< /C>。如果您想要更高的精度,请查看。

c程序根本不适用于我,
计数器+计数器+1行是错误的。这将是一个很好的起点。固定版本也会收敛到
0.999950
。您使用的是什么平台、编译器和编译器标志?您尝试过双精度而不是浮点吗?发现了我的错误。当然,对于double,它总是正常工作,而对于float,只有在不使用SSE2浮点数学时,它才会错误工作。