我想将此处出现的Muller方法的伪代码(参见编号2)http://kilyos.ee.bilkent.edu.tr/~microwave/programs/utilities/numeric1/infoMuller.htm转换为c ++代码。
Muller方法的在线实现很多,但我想直接翻译这个特定的伪代码。以下是我目前还没有给出正确结果的信息。这里的问题不是错误。该程序可以正常工作并给出输出-只是输出不正确,这意味着我的算法是错误的。我很难完全理解穆勒的方法,这可能是事情出问题的原因。作为一个特定的例子,假设多项式f(x)= x ^ 4-3 * x ^ 3 + x ^ 2 +1,其起始点为p0 = 0.5,p1 = 1.0和p2 = 1.5,则得出1.38939。我省略了停止技术,因此它将始终运行100次迭代。请指出我的代码出了问题的地方。
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
const int N = 100;
double long p0 = 0.5;
double long p1 = 1.0;
double long p2 = 1.5;
double long fp0 = 1*pow(p0,4) - 3*pow(p0,3) + 1*pow(p0,2) + p0 + 1;
double long fp1 = 1*pow(p1,4) - 3*pow(p1,3) + 1*pow(p1,2) + p1 + 1;
double long fp2 = 1*pow(p2,4) - 3*pow(p2,3) + 1*pow(p2,2) + p2 + 1;
double long h1 = p1 - p0;
double long h2 = p2 - p1;
double long delta1 = (fp1-fp0)/h1;
double long delta2 = (fp2-fp1)/h2;
double long d = (delta2 - delta1)/(h2 + h1);
int i = 3;
double long E;
while (i <= N)
{
double long b = delta2 + h2*d;
double long D = sqrt(b*b - 4*fp2*d);
if ( abs(b - D) < abs(b + D) )
E = b + D;
else
E = b - D;
double long h = (-2*fp2)/E;
double long p = p2 + h;
cout << setprecision(15) << i << "\t" << p << endl;
p0 = p1;
p1 = p2;
p2 = p;
h1 = p1 - p0;
h2 = p2 - p1;
delta1 = (fp1 - fp0)/h1;
delta2 = (fp2 - fp1)/h2;
d = (delta2 - delta1)/(h2 + h1);
i++;
}
return 0;
}
答案 0 :(得分:1)
在最初对内部投反对票的抗议之后,我再次使用@alter igel和@ user4581301的建议来遍历我的代码,并意识到这确实是一个错误,因为我不明白代码只是盲目地翻译了一下。我现在了解反对票。
回答:由于p0,p1,p2确实需要在while循环中更新变量fp0,fp1,fp2。
更新的代码:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
const int N = 100;
double long p0 = 0.5;
double long p1 = 1.0;
double long p2 = 1.5;
double long fp0 = 1*pow(p0,4) - 3*pow(p0,3) + 1*pow(p0,2) + p0 + 1;
double long fp1 = 1*pow(p1,4) - 3*pow(p1,3) + 1*pow(p1,2) + p1 + 1;
double long fp2 = 1*pow(p2,4) - 3*pow(p2,3) + 1*pow(p2,2) + p2 + 1;
double long h1 = p1 - p0;
double long h2 = p2 - p1;
double long delta1 = (fp1-fp0)/h1;
double long delta2 = (fp2-fp1)/h2;
double long d = (delta2 - delta1)/(h2 + h1);
int i = 3;
double long E;
while (i <= N)
{
double long b = delta2 + h2*d;
double long D = sqrt(b*b - 4*fp2*d);
if ( abs(b - D) < abs(b + D) )
E = b + D;
else
E = b - D;
double long h = (-2*fp2)/E;
double long p = p2 + h;
cout << setprecision(15) << i << "\t" << p << endl;
p0 = p1;
p1 = p2;
p2 = p;
//update of fp0, fp1, fp2
fp0 = 1*pow(p0,4) - 3*pow(p0,3) + 1*pow(p0,2) + p0 + 1;
fp1 = 1*pow(p1,4) - 3*pow(p1,3) + 1*pow(p1,2) + p1 + 1;
fp2 = 1*pow(p2,4) - 3*pow(p2,3) + 1*pow(p2,2) + p2 + 1;
h1 = p1 - p0;
h2 = p2 - p1;
delta1 = (fp1 - fp0)/h1;
delta2 = (fp2 - fp1)/h2;
d = (delta2 - delta1)/(h2 + h1);
i++;
}
return 0;
}