[英]Roots of Legendre Polynomials c++
我正在編寫一個程序,使用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;
}
假設我確實有起作用的勒讓德多項式和勒讓德多項式導數生成函數,但我認為這樣做會使代碼文本難以理解。 從返回數組計算值的意義上講,此函數起作用,但是它們卻大相徑庭,輸出以下內容:
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 ++中所做的沒有任何不同,因此,感謝任何人對此提供的任何幫助。 作為參考,我主要嘗試模仿Rosetta代碼上有關高斯正交的方法: 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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.