我正在尝试编写代码来使用错误位置方法找到非线性方程的根。
我已经完成了我的代码,但我仍然有一个问题。例如,如果我知道根在 5 和 6 之间。所以我输入上限为 7,下限输入 6。我仍然得到根。即使两个初始猜测没有包含根,我也不明白错误位置方法如何收敛。
这是我的代码:
void main()
{
std::cout << "Enter the First Limit: " << std::endl;
double x1;
std::cin >> x1;
std::cout << "Enter The Second Limit: " << std::endl;
double x2;
std::cin >> x2;
std::cout << "\nThe root = " << iteration(x1,x2); << std::endl;
}
double f(double x)
{
return pow(x,3) - 8*pow(x,2)+12*x-4;
}
// Evaluating the closer limit to the root
// to make sure that the closer limit is the
// one that moves and the other one is fixed
inline bool closerlimit(double u, double l)
{
return fabs(f(u)) > fabs(f(l)));
}
double iteration(double u, double l)
{
double s=0;
for (int i=0; i<=10; i++)
{
s = u - ((f(u)*(l-u)) / (f(l)-f(u)));
if (closerlimit(u,l))
l = s;
else
u = s;
}
return s;
}