为什么在c ++中实现高斯勒让德算法不会产生结果?

时间:2017-03-26 08:37:45

标签: c++ algorithm pi

我正在学习c ++,我在维基百科上发现了Gauss-Legendre算法来近似pi(链接:https://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm)。 我尝试用c ++实现它,但它没有产生任何结果。 这是代码:

#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <iomanip.h>
int main()
    {
        clrscr();
        long double a0 = 1,
                b0 = 1 / sqrt(2),
                t0 = 1 / 4,
                p0 = 1,
                an, bn, pn, tn;
    int i = 0;
    while(i < 3)
    {
        an = (a0 + b0) / 2;
        bn = sqrt(a0 * b0);
        tn = t0 - (p0 * (pow((a0 - an), 2)));
        pn = 2 * p0;
        a0 = an;
        b0 = bn;
        t0 = tn;
        p0 = pn;
    }
    long double pi = (pow((an + bn), 2)) / (4 * tn);
    cout<<pi;
    getch();
    return 0;
  }

当我寻求帮助时,我发现了这个,但在我看来它是一个不同的算法 - gauss-legendre in c++

更新:添加i增量程序后会产生错误的结果。

3 个答案:

答案 0 :(得分:1)

您不会在i循环中增加while

答案 1 :(得分:0)

除了你的while循环变量没有更新这一事实你还宣布你的双打不正确。声明双打时,例如&#34; 1/4&#34;,将它们写为&#34; 1.0 / 4.0&#34;是一种很好的做法。或&#34; 1 / 4.0&#34;如果你很懒惰。

原因是C / C ++将执行&#34; /&#34;运算符在整数上并在事后执行类型转换。基本上你的t0 = 0(你可以自己检查)。

这是您的代码,只需进行一些修改即可在每次循环迭代时打印完整的双精度。

#include <iostream>
#include <cmath>
#include <limits>

int main()
{
  long double a0=1.0, b0 = 1/sqrt(2),
   t0 = 1.0/4.0, p0 = 1.0;
  long double an,bn,pn,tn;
  int i = 0;
  long double pi;
  typedef std::numeric_limits<double> dbl;
  std::cout.precision(dbl::max_digits10);
  while(i < 4)
    {
      an = (a0 + b0)/2.0;      
      bn = sqrt(a0 * b0);
      tn = t0 - (p0 * (a0-an)*(a0-an));
      pn = 2*p0;
      a0 = an,b0 = bn,p0 = pn,t0 = tn;

      pi = (an+bn)*(an+bn) / (4*tn);
      std::cout << pi << std::endl;      
      i++;
    }
  return 0;
}

答案 2 :(得分:-1)

编辑: 1.添加行i ++; 2.更改此代码 -

while(i < 3)
{
    an = (a0 + b0) / 2;
    bn = sqrt(a0 * b0);
    tn = t0 - (p0 * (pow((a0 - an), 2)));
    pn = 2 * p0;
    a0 = an;
    b0 = bn;
    t0 = tn;
    p0 = pn;
}

- 至

while(i < 3)
{
    an = (a0 + b0) / 2;
    bn = sqrt(a0 * b0);
    pn = 2 * p0;
    tn = t0 - (p0 * (pow((a0 - an), 2)));
    a0 = an;
    b0 = bn;
    t0 = tn;
    p0 = pn;
    i++;
}

将pn放在tn。

之上