正弦函数拟合c++代码
时间: 2024-10-17 16:05:11 浏览: 32
在C++中,我们可以使用最小二乘法对数据进行正弦函数拟合。这里提供一个简单的示例,假设我们有一个包含x值和y值的一维数组,我们要找到一个正弦曲线y = A * sin(B * x + C) + D最接近原始数据。以下是一个基本的步骤:
```cpp
#include <iostream>
#include <cmath>
#include <vector>
// 定义正弦函数
double sine(double x, double a, double b, double c, double d) {
return a * std::sin(b * x + c) + d;
}
// 拟合函数,使用最小二乘法
std::tuple<double, double, double, double> fit_sine(const std::vector<double>& x_data, const std::vector<double>& y_data) {
double sum_x = 0, sum_y = 0, sum_xy = 0, sum_xx = 0, n = x_data.size();
for (size_t i = 0; i < n; ++i) {
double xi = x_data[i], yi = y_data[i];
sum_x += xi;
sum_y += yi;
sum_xy += xi * yi;
sum_xx += xi * xi;
}
// 使用公式计算系数
double a = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);
double b = (n * sum_xx * sum_y - sum_x * sum_xy) / (n * sum_xx * sum_xx - sum_x * sum_x);
double c = -asin(a / sqrt(1 - pow(a, 2))) / b;
double d = (sum_y - a * std::sin(c * sum_x) - b * c) / n;
return std::make_tuple(a, b, c, d);
}
int main() {
// 示例数据
std::vector<double> x_data = {0, M_PI / 2, M_PI, 3 * M_PI / 2, 2 * M_PI};
std::vector<double> y_data = {0, 1, 0, -1, 0};
auto coefficients = fit_sine(x_data, y_data);
std::cout << "拟合后的正弦函数: y = ";
for (const auto& coef : coefficients) {
if (coef != 0)
std::cout << coef << "*";
else
std::cout << "0*";
}
std::cout << "sin(x) + offset\n";
return 0;
}
```
阅读全文