上了个数值分析 代码写的头痛 码着再说 插值方法部分
拉格朗日插值、牛顿插值、线性拟合方法
#include<iostream>
using namespace std;
//预先定义插值节点的个数为1000个,根据控制台输入的个数num从而确定插值节点的个数
const int N = 1000;
//arrX[N],arrY[N]分别存放的是插值节点(Xi,Yi)中的Xi,Yi,参数n为插值节点的个数,而参数x为待求解的插值节点的X值
//函数返回值为求解出来的插值节点x对应的y值
//注意整个过程涉及的变量,除了循环变量为int外,其他均为float
float Lagrange(float arrX[],float arrY[],int n,float x){
float yResult=0.0;
//LValue[N]存放的是每次求解的插值基函数的通项
float LValue[N];
//循环变量k,m
int k,m;
//插值基函数中的上下累乘temp1,temp2
float temp1,temp2;
for(k=0; k<n; k++)
{
temp1 = 1.0;//分子和分母不能为0,所以初始化为1.0
temp2 = 1.0;
for(m=0; m<n; m++)
{
if(m==k)
{
continue;
}
temp1 *=(x-arrX[m]);//插值公式的分子部分。(x-x1)(x-x2)
temp2 *=(arrX[k]-arrX[m]);//插值公式的分母部分(x0-x1)(x1-x2)
}
LValue[k] = temp1/temp2;//求出的一个分式
}
for(int i=0; i<n; i++)
{
yResult += arrY[i]*LValue[i];//求出和
}
return yResult;
}
/*
case:
3
144 12
121 11
100 10
115
10.7228
*/
/*
float Newton(float arrX[], float arrY[], int n, float x) {
float quantient[N];
float sum = 0; int i = 0;
quantient[0] = arrY[0];
for ( i= 1; i < n; i++) {
for (int k = 0; k < i; k++) {
float result = 1;
for (int j = 0; j <n; j++) {//差商的分母项
if (j != k)
result *= (arrX[k] - arrX[j]);
}
sum+= arrY[k] / result;//i阶差商存在数组中
}
quantient[i] = sum;
cout << sum<<endl;
sum = 0;
}
cout << quantient[0] << quantient[1] << quantient[2];
float multipleresult = 1;
float result =arrY[0] ;
for (int j = 1; j < n + 1; j++) {
multipleresult *= (x - arrX[j-1]);
result += (quantient[j] * multipleresult);
}
return result;
}
*/
float Newton(float arrX[],float arrY[],int n, float x) {
float newton[10][10];
float result=0;
float m = 1;
for (int i = 0; i < n; i++) {
newton[0][i] = arrY[i];
}
for (int i = 1; i < n; i++) {
for (int j = i; j < n; j++) {
newton[i][j] = (newton[i - 1][j] -newton[i - 1][j - 1]) / (arrX[j] - arrX[j - i]);
}
}
for (int i = 0; i < n; i++) {
result +=( newton[i][i] * m);
m *=( x - arrX[i]);
}
return result;
}
void linearestimate(float arrX[], float arrY[], int n) {
float sum_Xi=0, sum_Xisquare=0, sum_XiYi=0, sum_Yi=0;
for (int i = 0; i < n; i++) {
sum_Xi += arrX[i];
sum_Xisquare += arrX[i] * arrX[i];
sum_XiYi += arrX[i] * arrY[i];
sum_Yi += arrY[i];
}
float a, b;
b = ((sum_Xi * sum_Yi) -n* sum_XiYi)/(sum_Xi*sum_Xi-n*sum_Xisquare);
a = (sum_XiYi - b * sum_Xisquare) / sum_Xi;
cout << "y=" << a;
if (b > 0)
cout << "+" << b<<"x";
else
cout << b<<"x";
}
/*
case:
5
165
187
123
126
150
172
123
125
141
148
y=-60.9392+1.5138x
*/

浙公网安备 33010602011771号