采用二分法求函数极大值和极小值。
xaml代码:
<Grid>
<StackPanel>
<Button Name="colum" Width="120" Height="30" Margin="30,30,0,0" Click="colum_Click">计算最大值</Button>
<TextBox Name="result" Width="120" Height="30" Margin="30,10,0,0"></TextBox>
<Button Name="colum2" Width="120" Height="30" Margin="30,30,0,0" Click="colum2_Click">计算最小值</Button>
<TextBox Name="result2" Width="120" Height="30" Margin="30,10,0,0"></TextBox>
</StackPanel>
</Grid>
自定义函数:
static double TargetFunction(double x)
{
// 示例函数:
return x * x*x-x-2;
}
二分法求极大值代码:
// 使用二分法寻找函数的最大值
static double FindMaximumWithBinarySearch(double start, double end, double tolerance)
{
double mid;
while (end - start > tolerance)
{
if(TargetFunction(start)< TargetFunction(end))
{
mid = (end + start) / 2;
if(TargetFunction(mid) < TargetFunction(end))
{
start=mid;
}
else
{
start = mid;
}
}
else
{
mid = (end + start) / 2;
if (TargetFunction(mid) < TargetFunction(end))
{
end = mid;
}
else
{
end= mid;
}
}
}
return TargetFunction((start+end)/2);
}
二分法求极小值代码:
// 使用二分法寻找函数的最小值
static double FindMinmumWithBinarySearch(double start, double end, double tolerance)
{
double mid;
while (end - start > tolerance)
{
mid = (start + end) / 2;
if (TargetFunction(start) < TargetFunction(end))
{
if (TargetFunction(start) < TargetFunction(mid))
{
end = mid;
}
else
{
end = mid;
}
}
else
{
if (TargetFunction(end) < TargetFunction(mid))
{
start = mid;
}
else
{
start = mid;
}
}
}
return TargetFunction((start+end)/2);
}
按钮“计算最大值”实例代码:
private void colum_Click(object sender, RoutedEventArgs e)
{
// 起始点和结束点
double start = -2;
double end = 10;
// 精度
double epsilon = 0.00001;
// 求解
double maximum = FindMaximumWithBinarySearch(start, end, epsilon);
result.Text = maximum.ToString();
}
按钮“计算最小值”实例代码:
private void colum2_Click(object sender, RoutedEventArgs e)
{
double start = -2;
double end = 10;
double tolerance = 0.00001; // 容忍度
double minum = FindMinmumWithBinarySearch(start, end, tolerance);
result2.Text= minum.ToString();
}
计算结果显示: