勒让德多项式c++
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;
}
假设函数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。
相关文章:
- c++模板来表示多项式
- 使用链表数据结构打印多项式
- 需要帮助重载多项式类运算符C++
- 如何修复此教科书程序以在C++中添加多项式?
- 如何对两个 4 位数字进行乘法,将它们视为 C++ 中的多项式
- 实现伪多项式DP子集和
- 递归程序获得勒让德多项式
- 在 NTL 中构造多项式的标准方法是什么?
- 最小二乘多项式拟合仅适用于偶数个坐标
- 多项式系数代码始终提供相同的答案
- 进入第二个多项式后如何修复分割错误?
- 用霍纳方法进行多项式求值的C++ constexpr
- 卡拉苏巴 - 多项式乘以 CUDA
- 使用链表添加多项式?援助
- 用Isringstream C 提取多项式的系数
- 用于多项式乘法的卡拉苏巴算法
- C :多项式矩阵的输出
- 多项式链接列表中的过载 运算符
- NTRUEncrypt:使用开源标准算法中的描述无法正确找到两个多项式的GCD,无法定义是否存在多边形的逆
- 二阶多项式计算器的输出不一致