1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
| #include <Eigen/Dense> #include <iostream> #include <fstream> #include <vector> #include <cmath>
using namespace Eigen; using namespace std;
double Lagrange(vector<Vector2d> points, double x, int n) { double result = 0; double L;
for (int k = 0; k < n; k++) { L = 1; for (int j = 0; j < n; j++) { if (j != k) { L = ((x - points[j][0]) / (points[k][0] - points[j][0]))*L; } } result += L * points[k][1]; }
return result; }
double Newton(vector<Vector2d> points, double x, int n) { double result = 0;
MatrixXd DQTable(n, n + 1); DQTable.setZero();
for (int i = 0; i < n; i++) { DQTable(i, 0) = points[i][0]; } for (int i = 0; i < n; i++) { DQTable(i, 1) = points[i][1]; } for (int j = 2; j < n + 1; j++) { for (int i = j - 1; i < n; i++) { DQTable(i, j) = (DQTable(i, j - 1) - DQTable(i - 1, j - 1)) / (DQTable(i, 0) - DQTable(i - j + 1, 0)); } }
double w = 1; for (int k = 0; k < n; k++) { if (k > 0) { w = w * (x - points[k - 1][0]); } result += w * DQTable(k, k + 1); }
return result; }
Vector2d CurveFit(vector<Vector2d> points, int n) { double sum_x = 0; double sum_x2 = 0; double sum_y = 0; double sum_xy = 0;
Matrix2d A; Vector2d b; Vector2d x;
for (int i = 0; i < n; i++) { sum_x += points[i][0]; sum_x2 += pow(points[i][0], 2); sum_y += points[i][1]; sum_xy += points[i][0] * points[i][1]; }
A(0, 0) = n; A(1, 0) = A(0, 1) = sum_x; A(1, 1) = sum_x2;
b(0) = sum_y; b(1) = sum_xy;
x = A.lu().solve(b);
return x; }
vector<Vector2d> ReadPointData(const string &path, double &x0) { vector<Vector2d> points;
ifstream ifs(path); if (!ifs.is_open()) return points;
ifs >> x0;
double x, y; while (!ifs.eof()) { ifs >> x >> y; points.push_back(Vector2d(x, y)); }
return points; }
int main() { vector<Vector2d> points; Vector2d v; double x;
points = ReadPointData("F://points1.txt", x); cout << endl << "拉格朗日插值:" << "f(" << x << ") = " << Lagrange(points, x, points.size()) << endl;
points = ReadPointData("F://points2.txt", x); cout << endl << "牛顿插值:" << "f(" << x << ") = " << Newton(points, x, points.size()) << endl;
points = ReadPointData("F://points3.txt", x); v = CurveFit(points, points.size()); cout << endl << "曲线拟合:" << "y = " << v[0] << " + " << v[1] << " * x" << endl;
return 0; }
|