#include
#include
using namespace std;
double function(double x)
{
return (2 * pow(x, 2) - x - 1);
}
class AR
{
protected:
double x0_, x1_, x2_, x3_, x4_, h0_;
public:
AR();
AR(double x0, double h0);
void Calculate1();
void change();
};
AR::AR()
{
x0_ = x1_ = x2_ = x3_ = x4_ = 0.0;
h0_ = 0.01;
}
AR::AR(double x0, double h0)
{
x0_ = x0;
x1_ = x2_ = x3_ = x4_ = 0.0;
h0_ = h0;
}
void AR::Calculate1()
{
int k;
double h;
k = 0;
h = h0_;
x1_ = x0_;
while (1)
{
k++;
x4_ = x1_ + h;
if (function(x4_) < function(x1_))
{
x2_ = x1_;
x1_ = x4_;
h *= 2;
}
else
{
if (k == 1)
{
h = -h;
x2_ = x4_;
}
else
{
x3_ = x2_;
x2_ = x1_;
x1_ = x4_;
cout << x1_ << " " << x2_ << " " << x3_ << '\n';
break;
}
}
}
}
//从小到大对X1,X2,X3排序
void AR::change()
{
double temp;
if (x1_> x3_);
{
temp = x1_;
x1_ = x3_;
x3_ = temp;
}
}
class Parabola :public AR
{
private:
double B1_, B2_, B3_, C1_, C2_, C3_, D_;
double b_, c_;
double x_;
double sigma_;
double deta_;
public:
Parabola();
Parabola(double a,double b, double sigma, double deta);
void Calculate2();
};
Parabola::Parabola()
{
B1_ = B2_ = B3_ = C1_ = C2_ = C3_ = D_ = 0.0;
b_ = c_ = 0.0;
x_ = 0.0;
sigma_ = 0.0;
}
Parabola::Parabola(double a, double b, double sigma, double deta):AR(a,b)
{
sigma_ = sigma;
deta_ = deta;
{
B1_ = (pow(x2_, 2) - pow(x3_, 2))*function(x1_);
B2_ = (pow(x3_, 2) - pow(x1_, 2))*function(x2_);
B3_ = (pow(x1_, 2) - pow(x2_, 2))*function(x3_);
C1_ = (x2_ - x3_)*function(x1_);
C2_ = (x3_ - x1_)*function(x2_);
C3_ = (x1_ - x2_)*function(x3_);
D_ = (x1_ - x2_)*(x2_ - x3_)*(x3_ - x1_);
}
{
b_ = (B1_ + B2_ + B3_) / D_;
c_ = -(C1_ + C2_ + C3_) / D_;
}
x_ = -b_ / (2 * c_);
}
void Parabola::Calculate2()
{
int k = 0;
double x_temp = 0.0;
{
B1_ = (pow(x2_, 2) - pow(x3_, 2))*function(x1_);
B2_ = (pow(x3_, 2) - pow(x1_, 2))*function(x2_);
B3_ = (pow(x1_, 2) - pow(x2_, 2))*function(x3_);
C1_ = (x2_ - x3_)*function(x1_);
C2_ = (x3_ - x1_)*function(x2_);
C3_ = (x1_ - x2_)*function(x3_);
D_ = (x1_ - x2_)*(x2_ - x3_)*(x3_ - x1_);
}
{
b_ = (B1_ + B2_ + B3_) / D_;
c_ = -(C1_ + C2_ + C3_) / D_;
}
x_ = -b_ / (2 * c_);
while (1)
{
k++;
x_temp = x_;
if (function(x2_) <= function(x_))
{
if (x_ < x3_&&x_>x2_)
x3_ = x_;
if (x_ < x2_&&x_>x1_)
x1_ = x_;
}
else
{
if (x2_ > x1_&&x2_ < x_)
x1_ = x2_;
if (x2_ > x_&&x2_ < x3_)
x3_ = x2_;
x2_ = x_;
}
{
B1_ = (pow(x2_, 2) - pow(x3_, 2))*function(x1_);
B2_ = (pow(x3_, 2) - pow(x1_, 2))*function(x2_);
B3_ = (pow(x1_, 2) - pow(x2_, 2))*function(x3_);
C1_ = (x2_ - x3_)*function(x1_);
C2_ = (x3_ - x1_)*function(x2_);
C3_ = (x1_ - x2_)*function(x3_);
D_ = (x1_ - x2_)*(x2_ - x3_)*(x3_ - x1_);
}
{
b_ = (B1_ + B2_ + B3_) / D_;
c_ = -(C1_ + C2_ + C3_) / D_;
}
x_ = -b_ / (2 * c_);
if ((abs(function(x_) - function(x_temp)) < sigma_) || (abs(x_ - x_temp) < deta_))
break;
}
cout << "极小点是:" << x_ << " " << "其函数值是:" << function(x_) << '\n';
}
int main()
{
Parabola par(0.0, 0.001,0.1, 0.1);
par.Calculate1();
par.Calculate2();
while (1);
}
结合进退法和抛物线法的一维搜索程序
最新推荐文章于 2021-05-29 05:02:11 发布