简体   繁体   English

勒让德多项式的根c ++

[英]Roots of Legendre Polynomials c++

I'm writing a program to find the roots of nth order Legendre Polynomials using c++; 我正在编写一个程序,使用c ++查找n阶勒让德多项式的根。 my code is attached below: 我的代码附在下面:

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;
}

Assuming the existence of functioning Legendre Polynomial and Legendre Polynomial derivative generating functions, which I do have but I thought that would make for unreadable walls of code text. 假设我确实有起作用的勒让德多项式和勒让德多项式导数生成函数,但我认为这样做会使代码文本难以理解。 This function is functioning in the sense that it's returning an array calculated values, but they're wildly off, outputting the following: 从返回数组计算值的意义上讲,此函数起作用,但是它们却大相径庭,输出以下内容:

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

where an equivalent function I've written in Python gives the following: 我在Python中编写的等效函数给出了以下内容:

[-0.90617985 -0.54064082  0.          0.54064082  0.90617985]

I was hoping another set of eyes could help me see what the issue in my C++ code is that's causing the values to be wildly off. 我希望另一组眼睛可以帮助我了解C ++代码中的问题是什么导致值急剧下降。 I'm not doing anything different in my Python code that I'm doing in C++, so any help anyone could give on this is greatly appreciated, thanks. 我在Python代码中所做的工作与在C ++中所做的没有任何不同,因此,感谢任何人对此提供的任何帮助。 For reference, I'm mostly trying to emulate the method found on Rosetta code in regards to Gaussian Quadrature: http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature . 作为参考,我主要尝试模仿Rosetta代码上有关高斯正交的方法: http : //rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature

You are returning an address to a temporary variable in stack 您正在将地址返回到堆栈中的临时变量

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

I suggest changing your function definition to 我建议将您的函数定义更改为

void legRoots(int n, double *myRoots)

omitting the return statement, and defining myroots before calling the function 省略return语句,并在调用函数之前定义myroots

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

Option 2 would be to allocate myRoots dynamically with new or malloc. 选项2是使用new或malloc动态分配myRoots。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM