假位法(需要帮助)
我正在尝试编写代码来使用假位置法查找非线性方程的根。
我的代码已经完成,但仍然有问题。 例如,如果我知道根在 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;
}
I'm attempting to write a code to find the root of non-linear equations using the false position method.
I'm done with my code, but I still have a problem.
For example, if I know that the root is between 5 and 6.
so I enter the upper limit as 7 and the lower at 6.
I still get the root.
I don't understand how the false position method converges even when the two initial guesses are not bracketing the root.
Here is my code:
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的函数图和根:
Your function plot and roots:
但间隔是把根括起来的。
But the interval IS bracketing the root.