Brent's Method of Realizing Extreme Value in C++

Brent's Method of Realizing Extreme Value in C++

Brent's method is a very effective method for finding the extremum, and it is more suitable for solving the local minimum of continuous functions. This article will use C++ to implement this algorithm, and provide complete source code and corresponding description.

Principles of the Brent Method

Brent's method is an iterative method for finding the minimum of a continuous function in one dimension. Its main idea is to find an interval whose length gradually shrinks with the number of iterations, so that the value of the function in this interval continues to approach the minimum value.

Specifically, the algorithm first needs to choose three points x1, x2 and x3, where x2 is the middle point. Then construct a quadratic interpolation function based on the function values ​​f(x1), f(x2) and f(x3) of these three points. Through this function, the minimum value can be found and the values ​​of x1, x2 and x3 can be updated to reduce the length of the interval. This process is repeated until a certain accuracy requirement is met or the maximum number of iterations is reached.

C++ source code implementation

In the C++ code that implements Brent's method, we need to define a structure of three points and a function for calculating the value of the function. The specific code is as follows:

#include <iostream>
#include <cmath>

using namespace std;

const double EPS = 0.00001; //算法精度
const int MAX_ITERATIONS = 1000; //最大迭代次数

//定义结构体存储函数的三个点
struct Point {
    double x;
    double y;
};

//计算函数的值
double f(double x) {
    return (x-2)*(x-2)+3; //这里以(x-2)²+3为例
}

//布伦特方法求解函数的极小值
double brent(Point &pt1, Point &pt2, Point &pt3) {

    double x1 = pt1.x, x2 = pt2.x, x3 

Guess you like

Origin blog.csdn.net/Jack_user/article/details/132440367