4参数拟合

#include 
#include 
#include 
#include 

using namespace std;

// 定义拟合模型
double fit_func(double a, double b, double c, double d, double x) {
    return a + b / (1 + c * exp(-d * x));
}

// 定义四参数法曲线拟合函数
void four_para_fit(vector<double>& x, vector<double>& y, double& a, double& b, double& c, double& d) {
    double sum_x = accumulate(x.begin(), x.end(), 0.0);
    double sum_y = accumulate(y.begin(), y.end(), 0.0);
    double sum_xy = inner_product(x.begin(), x.end(), y.begin(), 0.0);
    double sum_x2 = inner_product(x.begin(), x.end(), x.begin(), 0.0);
    double n = x.size();

    double x_avg = sum_x / n;
    double y_avg = sum_y / n;
    double xy_avg = sum_xy / n;
    double x2_avg = sum_x2 / n;

    // 计算 c 和 d
    double p = 100.0 * y_avg / b;
    double q = 100.0 * (y_avg - a) / b;
    c = p / q;
    d = log((1.0 / c) - 1.0) / x_avg;

    // 计算 a 和 b
    a = y_avg - b / (1.0 + c * exp(-d * x_avg));
    b = (xy_avg - a * sum_x - b * sum_x2 + a * x_avg * n + b * x_avg) / (x2_avg - 2.0 * x_avg * sum_x + n * x_avg * x_avg);
}

int main() {
    // 初始化数据
    vector<double> x = {1, 2, 3, 4, 5, 6};
    vector<double> y = {0.22, 0.44, 0.68, 0.81, 0.89, 0.94};
    double a, b, c, d;

    // 进行四参数法曲线拟合
    four_para_fit(x, y, a, b, c, d);

    // 输出拟合结果
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    cout << "c = " << c << endl;
    cout << "d = " << d << endl;

    return 0;
}

你可能感兴趣的:(算法)