进退法是用来确定极值区间的算法。依据为f(x)只有一个极小值,且[a,b]为极小值的一个搜索区间,对任意的x1,x2∈[a,b],如果f(x1)<f(x2),则[a,x2]为极小点的搜索区间,如果f(x1)>f(x2),则[x1,b]为极小值的搜索区间。
因此,在给定初始点x0,及初始搜索步长h的情况下,首先以初始步长向前搜索一步,计算f(x0+h);
(1)如果f(x0)<f(x0+h)
则可知搜索区间为[~,x0+h],~待求,为确定~,后退一步计算f(x0-λh),λ为缩小系数,且0<λ<1,直到找到合适的λ,使得f(x0-λ*h)>f(x0),从而确定搜索区间[x0-λ*h,x0+h];
(2)如果f(x0)>f(x0+h)
则可知搜索区间为[x0,~],~待求,为确定~,前进一步计算f(x0+λh),λ为放大系数,且λ>1,直到找到合适的λ,使得f(x0+h)<f(x0+λ*h),从而确定搜索区间[x0,x0+λh];
具体代码如下:
xaml代码:
<Grid>
<StackPanel>
<Button Height="40" Width="220" Margin="70,20,0,20" HorizontalAlignment="Left" FontSize="16" Click="Button_Click">计算极值区间</Button>
<Label Height="40" Width="120" Margin="70,0,0,0" HorizontalAlignment="Left" FontSize="16">区间左端点</Label>
<Label Height="40" Width="120" Margin="70,0,0,0" HorizontalAlignment="Left" FontSize="16">区间右端点</Label>
</StackPanel>
<StackPanel>
<TextBox Name="a" Height="40" Width="120" Margin="170,75,0,0" HorizontalAlignment="Left" FontSize="16"></TextBox>
<TextBox Name="b" Height="40" Width="120" Margin="170,0,0,0" HorizontalAlignment="Left" FontSize="16"></TextBox>
</StackPanel>
</Grid>
自定义函数代码:
/// <summary>
/// 自定义函数
/// </summary>
/// <param name="x">变量</param>
/// <returns></returns>
static double F(double x)
{
return x * x * x * x - x * x - 2 * x + 5;
}
进退法代码:
/// <summary>
/// 进退法搜索极值区间
/// </summary>
/// <param name="x0">初始点</param>
/// <param name="h0">初始步长</param>
/// <returns></returns>
static double[] JTmin(double x0, double h0)
{
double x1 = x0;
double k = 0;
double h = h0;
double x2=double.NegativeInfinity;
double x3=double.NegativeInfinity;
double x4=double.NegativeInfinity;
while (true)
{
x4 = x1 + h;
k = k + 1;
if (F(x4) < F(x1))
{
x2 = x1;
x1 = x4;
h = 2 * h;
}
else
{
if (k == 1)
{
h = -h;
x2 = x4;
}
else
{
x3 = x2;
x2 = x1;
x1 = x4;
break;
}
}
}
double minx = Math.Min(x1, x3);
double maxx = x1 + x3 - minx;
double[] res = {minx, maxx};
return res;
}
实例验证:
private void Button_Click(object sender, RoutedEventArgs e)
{
double x0 = 0;
double h0 = 0.1;
double[] res=JTmin(x0, h0);
a.Text = res[0].ToString();
b.Text = res[1].ToString();
}