某乡镇企业2010-2016年的大致生产利润如下表,试采用正确的方法预测2017和2018年的利润
年份 2010 2011 2012 2013 2014 2015 2016
利润(万元) 70 122 144 152 174 196 202
#include<iostream>
#include<math.h>
#include<vector>
using namespace std;
double x[7], y[7];
double table[8][8];
struct Newtoninterpolation {
Newtoninterpolation() {
x[0] = 2010, y[0] = 70;
x[1] = 2011, y[1] = 122;
x[2] = 2012, y[2] = 144;
x[3] = 2013, y[3] = 152;
x[4] = 2014, y[4] = 174;
x[5] = 2015, y[5] = 196;
x[6] = 2016, y[6] = 202;
}
public:
void Lagrangeinterpolation_solution(double _x) {
double result=0.0, t = 0;
for (int i = 0; i < 7; i++) {
t = 1;
for (int j = 0; j < 7; j++) {
if (j != i)
t *= (_x - x[j]) / (x[i] - x[j]);
}
result += t * y[i];
}
cout << _x << "的拉格朗日插值为:" <<result<<endl;
}
void Newton_solution() {
for (int i = 0; i < 7; i++)
table[i][0] = y[i];
for (int i = 1; i <= 7; i++) {
for (int j = 1; j <= i; j++) {
table[i][j] = (table[i][j - 1] - table[i - 1][j - 1]) / (x[i] - x[i - j]);
}
}
cout << "差商表:" << endl;
for (int i = 0; i < 7; i++) {
for (int j = 0; j <= i; j++) {
cout << table[i][j] << " ";
}
cout << endl;
}
cout << "2017估计值:" << endl;
double a = 2017, result = 0, c = 1;
for (int i = 0; i < 7; i++) {
result += table[i][i] * c;
c *= (a - x[i]);
}
cout << result << endl;
a = 2018, result = 0, c = 1;
cout << "2018估计值:" << endl;
for (int i = 0; i < 7; i++) {
result += table[i][i] * c;
c *= (a - x[i]);
}
cout << result << endl;
}
void fitting_process(long long _x) {
long long a, b;
long long a1[2][3] = { 0 }, c1[2][3] = {0};
long long r = 0;
long long r1 = 0;
a1[0][0] = 7;
for (int i = 0; i < 7; i++) {
a1[0][2] =a1[0][2]+ y[i];
a1[1][2] =a1[1][2]+ x[i] * y[i];
}
// cout<<c1[0][0]<<" "<<c1[1][0]<<endl;
for (int i = 0; i < 7; i++) {
r =r + x[i];
r1 =r1 + (x[i] * x[i]);
}
a1[0][1] = r;
a1[1][0] = a1[0][1];
a1[1][1]=r1;
long long k = a1[1][0] / a1[0][0];
for (int j = 0; j < 3; j++) {
a1[1][j] =a1[1][j] - a1[0][j] * k;
}
b = a1[1][2] / a1[1][1];
a=(a1[0][2] - a1[0][1] * b) / a1[0][0];
cout << "线性拟合"<<_x << "年的预测是:" << a + b * _x << endl;
}
};
int main() {
cout << "1707004347--黄洪飞" << endl;
Newtoninterpolation newtoninterpolation;
newtoninterpolation.Lagrangeinterpolation_solution(2017);
newtoninterpolation.Lagrangeinterpolation_solution(2018);
newtoninterpolation.Newton_solution();
newtoninterpolation.fitting_process(2017);
newtoninterpolation.fitting_process(2018);
system("pause");
return 0;
}