勒让德多项式c++

Roots of Legendre Polynomials c++

本文关键字:c++ 多项式      更新时间:2023-10-16

我正在编写一个程序,用c++查找n阶勒让德多项式的根;我的代码附在下面:

double* legRoots(int n)
{
 double myRoots[n];
 double x, dx, Pi = atan2(1,1)*4;
 int iters = 0;
 double tolerance = 1e-20;
 double error = 10*tolerance;
 int maxIterations = 1000;
 for(int i = 1; i<=n; i++)
 {
  x = cos(Pi*(i-.25)/(n+.5));
  do
  {
   dx -= legDir(n,x)/legDif(n,x);
   x += dx;
   iters += 1;
   error = abs(dx);
  } while (error>tolerance && iters<maxIterations);
  myRoots[i-1] = x;
 }
 return myRoots;
}

假设函数Legendre多项式和Legendre Polynomial导数生成函数的存在,我确实有,但我认为这会导致代码文本的墙无法阅读。这个函数的作用是返回一个数组计算值,但它们被严重关闭,输出以下内容:

3.95253e-323
6.94492e-310
6.95268e-310
6.42285e-323
4.94066e-323
2.07355e-317

其中,我用Python编写的等效函数给出了以下内容:

[-0.90617985 -0.54064082  0.          0.54064082  0.90617985]

我希望另一双眼睛能帮助我了解C++代码中导致值大幅偏离的问题。我在Python代码中没有做任何与C++不同的事情,所以任何人都能在这方面提供帮助,我们将不胜感激,谢谢。作为参考,我主要试图模仿罗塞塔代码中关于高斯正交的方法:http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature.

您正在向堆栈中的临时变量返回地址

{
    double myRoots[n];
    ...
    return myRoots; // Not a safe thing to do
}

我建议将您的功能定义更改为

void legRoots(int n, double *myRoots)

省略return语句,并在调用函数之前定义myroots

double myRoots[10];
legRoots(10, myRoots);

选项2是使用new或malloc动态分配myRoots。